Вы находитесь на странице: 1из 94

Aplicaciones Java

con Base de Datos Relacional

V8.0
Octubre 2015
Ferreiras

Ferreiras Aplicaciones JAVA, DB, JDBC 1


Importante
Complemento: Conjuntamente con
esta PPT, el profesor ha entregado el
archivo JDBCejemplo1Seccion.txt,
contenido en el comprimido
JDBCejemplo1.zip, en su grupo; Es
su responsabilidad realizar todo lo
indicado all. Please.

Ferreiras Aplicaciones JAVA, DB, JDBC 2


Coooomo ?!!
Pero aun no
hemos dado la
asignatura Base
de Dato I

No os
preocupis, el
seor guiar
sus ovejas
Ferreiras Aplicaciones JAVA, DB, JDBC 3
De un vistazo

Conceptos Bsicos
de Bases de Datos

Ferreiras Aplicaciones JAVA, DB, JDBC 4


Data
Notion about the data:

The word data covers the collection of facts stored in the database;

Data are the raw material from which information is generated;

Determining what data to enter into the database and how to organize those data is a vital part
of the database designers job.

Data are raw facts.

The word raw indicates that the facts have not ye been processed to reveal their meaning.

In the raw format are not particularly useful, so they must be transformed into a data summary to
be useful.

5
Data
Data concept.

Data are raw facts.

The word raw indicates that the facts have not ye been processed to reveal their meaning.

In the raw format are not particularly useful, so they must be transformed into a data summary to
be useful.

Some features of the data include:

Data constitute the building blocks of information.


Information is produced by processing data.
Information is used to reveal the meaning of data.
Accurate, relevant, and timely information is the key to good decision making.
Good decision making is the key to organizational survival in a global environment.

Data management

Focus on the proper generation, storage, and retrieval of data; Given the crucial role that data
play, it should not surprise that data management is a core activity for any business, government
agency, service organization, or charity.

Timely and useful information requires accurate data. Such data must be properly generated and
stored in a format that is easy to access and process. And, like any basic resource, the data
environment must be managed carefully. 6
Information
Data computationally processed, stored or transmitted.

The result of the data processing should be:

Accurate and timely,


Specific and organized with a purpose,
Presented in a context that gives meaning and relevance, and
That can lead to increased understanding and reduced uncertainty.

Information is valuable because it can affect behavior, a decision, or an


outcome.
The word data covers the collection of facts stored in the database;

Data are the raw material from which information is generated;

Determining what data to enter into the database and how to organize those
data is a vital part of the database designers job.

7
Data organization
It is the arrangement of raw data for its processing in order to converting
them into useful information.

The data organization is achieved by a data model, which standardizes


how its elements relate to each other.

Data organization also helps to clarify relationships between data items, by


putting related items in the same organizational element.

Data organization strategies are adopted in order to make better use of


the data assets that they have in a world where data sets represent some of
the most valuable assets held by enterprises across many different industries.

The Knowledge of the ways that data is commonly organized on a


computer will be helpful to work with new types of data and applications.

8
Structured and Unstructured
data
Structured Data are data organized in data structures which describe relationships
among data and operations over them;

Examples are Networked data structure, Hierarchical data structure, Tabular


data structure; This last is of interest in this course.

Unstructured data is data that is not organized and, therefore, has no predefined
data model or format specified; They are raw data without format.

Example of unstructured data is data that can be found in text documents (such
as names, dates ...).

9
Data integrity
The Data Integrity refers to the validity of data; Are data valid? Are data representing for
what they have been designed?

The following categories of the data integrity exist:

Entity Integrity: Ensures that there are no duplicate rows in a table.


Domain Integrity: Enforces valid entries for a given column by restricting the
type, the format, or the range of possible values.
Referential integrity: Ensures that rows cannot be deleted, which are used
by other records (for example, corresponding data values between tables will
be vital).
User-Defined Integrity: Enforces some specific business rules that do not
fall into entity, domain, or referential integrity categories.

Each of these categories of the data integrity can be enforced by using the
appropriate constraints ( see later Database Constraints ).

10
Datos
Los datos consisten de hechos en bruto,
tales como:
10008889112 Rafael 20

Pimentel fp@yahoo.com 1345.67

Para que los datos se transformen en


informacin til, se deben organizar de
una manera significativa. Es lo primero.

Ferreiras Aplicaciones JAVA, DB, JDBC 11


Una forma de organizar los datos es
en tablas identificadas, por ejemplo, los
datos anteriores pertenecen a un
estudiante, como se tendr mas de un
estudiante, su organizacin en una tabla
sera as:
ESTUDIANTES
matricula primerNombre primerApellido correoElectronico creditos totalPagar
10008889112 Rafael Pimentel rf@uasd.com 20 1345.56

Ferreiras Aplicaciones JAVA, DB, JDBC 12


Los elementos de la tabla Son, en trminos
generales: Nombre de la tabla, en plural y en
mayscula.

NombreDeLaTabla

filas
(tuplas)

columnas

Ferreiras Aplicaciones JAVA, DB, JDBC 13


Por ejemplo, En esta tabla INTERNOS:

INTERNOS
codigo nombre apellido pena
100000045 TOYOTA PEREZ 20
100045678 PERCIO CIVIC 13
100005678 LUIS CANOSO 30
100001333 MARIA CUQUITA 22

filas o registros con sus valores atmicos

columnas con sus nombres

nombre de la tabla Esto quiere decir que,


por ejemplo, Luisa Maria
NO es un valor atmico
para la columna nombre

Ferreiras Aplicaciones JAVA, DB, JDBC 14


Atomic Values
A piece of data in a database table that cannot be broken down any further (see
first normal form).

First normal form (1NF) is a property of a relation in a relational database. A


relation is in first normal form if the domain of each attribute contains only atomic
values, and the value of each attribute contains only a single value from that
domain.

Edgar F. Codd's definition of 1NF makes reference to the concept of 'atomicity'.


Codd states that the "values in the domains on which each relation is defined are
required to be atomic with respect to the DBMS."[6] Codd defines an atomic value
as one that "cannot be decomposed into smaller pieces by the DBMS (excluding
certain special functions)"[7] meaning a field should not be divided into parts with
more than one kind of data in it such that what one part means to the DBMS
depends on another part of the same field.

See http://en.wikipedia.org/wiki/First_normal_form
Ferreiras Aplicaciones JAVA, DB, JDBC 15
Base de Datos: En un sentido amplio,
una base de datos es cualquier cosa que
almacena datos relacionados. Por
ejemplo, la obsoleta (?) gua telefnica de
papel que almacena nombres y nmeros
telefnicos:
Importante: Cuando
usted vea este icono, le
estn indicando que ah
hay una gua telefnica,
de uso publico, no para
que usted le arranque
las paginas o se la
lleve. .

Ferreiras Aplicaciones JAVA, DB, JDBC 16


Informaticamente, Una base de datos,
se refiere a un conjunto de partes de
informacin almacenada electrnicamente
y organizada de manera tal que provee
una forma eficiente para que dicha
informacin se pueda, de manera rpida,
recuperar y actualizar aleatoriamente.

Ferreiras Aplicaciones JAVA, DB, JDBC 17


Jerarqua de los datos
Archivos

archivo de personal
Base de Datos
archivo de Ventas

archivo de nomina Registros

100023344 Pedro Pimentel 20 12345.67 3.5


100000456 Maria Lopez 5 545.23 2.3
Archivos
AB-7431 Jose Perez 25 2348.33 4.5

Campos

Registros 100000456 Maria Lopez 5 545.23 2.3

Campos Pedro Caracteres

Caracteres 01010000 Bits, ASCII STD 8 de la P


Ferreiras Aplicaciones JAVA, DB, JDBC 18
Esquema de la base de datos:
Normalmente, Para una determinada
base de datos, hay una descripcin
estructural del tipo de datos contenido,
Esta descripcin se conoce como el
esquema de la base de datos. El
esquema describe los objetos que
estn representados en la base de
datos, y las relaciones entre ellos.

Ferreiras Aplicaciones JAVA, DB, JDBC 19


Organizar un esquema es Modelar
los Datos: Hay un nmero de formas
diferentes de organizar un esquema, es
decir, de modelar la estructura de la base
de datos, estos son conocidos como
modelos de bases de datos (o los
modelos de datos).

En el tema Introduccin al Modelado


de Datos, de la asignatura INF-526,
con el profesor Ferreiras, usted
trabajara y construir este
conocimiento.
Ferreiras Aplicaciones JAVA, DB, JDBC 20
El modelo mas comn De una base
de datos es un modelo relacional. Esas
bases de datos estn organizadas por
campos, registros y tablas. Un campo es
una sola pieza de informacin, un registro
es un conjunto completo de los campos, y
una tabla es una coleccin de registros.
Con este modelo simple, apenas alrededor
de cualquier relacin entre una recogida
de datos se pueden representar.

Ferreiras Aplicaciones JAVA, DB, JDBC 21


Un Modelo Relacional De
Datos, percibe o ve los datos
organizados en forma de tablas,
como coleccin de filas y columnas
conteniendo solamente valores
atmicos como un todo.

Ferreiras Aplicaciones JAVA, DB, JDBC 22


De un vistazo

Servidor de Base da datos


o SGBD

Ferreiras Aplicaciones JAVA, DB, JDBC 23


Servidor de Base de Datos
Es Una coleccin de programas que
permite crear una base de datos y
almacenar, modificar y extraer
informacin de sta. Es un sistema de
software utilizado para administrar una
base de datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 24


Un Servidor de bases de datos
( Data Server ) es un Sistema de Gestin
de Base de Datos, SGBD ( DataBase
Management System, DBMS ). Otros
nombres son Administrador de base de
datos, o, simplemente, la base de
datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 25


Un SGBD relacional usa un
Lenguaje de Definicin de Datos, el cual
tiene una sintaxis similar a los lenguajes
de programacin, para crear las tablas,
definiendo sus registros y campos en los
que se organizar la informacin
internamente. ( Ver SQL mas adelante )

Ferreiras Aplicaciones JAVA, DB, JDBC 26


Dos tipos de SGBD:

SGBD PC ( data files ): MS Access,


Dbase, Paradox, Btrieve, ...

SGBD SQL: MySQL, Oracle, MS SQL


Server, Sybase, Informix, IBM DBe, Derby,
Ingres, ...

MS Access encaja en las dos categoras.

Ferreiras Aplicaciones JAVA, DB, JDBC 27


Los SGBD mas comunes1 hoy da son:
MySQL
IBM DB2 Para este pequeo, muy
Oracle
pequeo nivel
introductorio, usaremos
PostgreSQL (ORDBMS)
ste SGBD, el cual es un
Derby ( Java DB)
sistema de base de
Ingres datos que esta
MS SQL SERVER embebido (integrado)
en la JVM
...

1:Ver lista mas amplia en:


http://en.wikipedia.org/wiki/List_of_relational_database_management_systems

Ferreiras Aplicaciones JAVA, DB, JDBC 28


Un sistema de base de datos integrada Es un
SGBD que est estrechamente integrado con un
software de aplicacin que requiere acceso a los
datos almacenados, de manera que el sistema de
base de datos est "oculto" de la aplicacin del
usuario final; Se incluye con una aplicacin en vez
de ofrecerse por separado y se utiliza, por ejemplo,
en telfonos celulares, PDAs y otros dispositivos
dedicados.

Ferreiras Aplicaciones JAVA, DB, JDBC 29


De un vistazo

Accesando a bases de
datos

Ferreiras Aplicaciones JAVA, DB, JDBC 30


Accesando a la base de datos
Acceder a una base de datos Es acceder
a su estructura y a la informacin
almacenada en ella. Para ello lo primero es
identificarse con la base de dato. Esto es
conocido como conectarse con la base de
datos. Para conectarse con la base de
datos se necesita un controlador para
dicha base de datos en particular.

Ferreiras Aplicaciones JAVA, DB, JDBC 31


Un controlador de base de datos Es una
rutina de software que accede una base de
datos. Permite a la aplicacin del usuario
interactuar con la base de datos, con sus
tablas, en un RDBMS:

Base
aplicacin controlador SGBD de
Datos

Conecta la
aplicacin con la
base de datos a
travs del SGBD

Ferreiras Aplicaciones JAVA, DB, JDBC 32


Controladores de base de datos:

Nativo
Es un controlador especifico, escrito para conectar con una
aplicacin en especifico. Por ejemplo, un controlador nativo para
conectar Crystar Report ( un generador de reportes ) a una base de
datos.

ODBC
ODBC Son las siglas de Open DataBase Connectivity, y significa
que cualquier base de datos que cumpla con esta norma se puede
comunicar con otras aplicaciones que se ajusten al estndar ODBC.

Ferreiras Aplicaciones JAVA, DB, JDBC 33


Controladores de base de datos:

JDBC
JDBC son las siglas de Java DataBase Connectivity. Es un API de
Java compuesta por un conjunto de clases que se puede utilizar para
desarrollar aplicaciones Java que necesitan acceder a una base
relacional de datos.

...

Ferreiras Aplicaciones JAVA, DB, JDBC 34


De un vistazo

JDBC
[ Java DataBase Connectivity ]

Ferreiras Aplicaciones JAVA, DB, JDBC 35


JDBC
JDBC son las siglas de Java DataBase
Connectivity. Es un API de Java compuesta
por un conjunto de clases que se puede
utilizar para desarrollar aplicaciones Java
que necesitan acceder a una base
relacional de datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 36


El controlador JDBC Es independiente
de cualquier implementacin especfica del
proveedor del SGBD, por lo que hace que
las aplicaciones sean porttiles. Por
ejemplo, si escribe una aplicacin de base
de datos usando Oracle, la misma
aplicacin funcionar para MySQL con
mnimas modificaciones

Ferreiras Aplicaciones JAVA, DB, JDBC 37


JDBC es un API de Java que permite a los programas de Java
ejecutar sentencias SQL, posibilitando as que estos puedan
interactuar con cualquier base de datos compatible con SQL.

Puesto que casi todos DBMS relacionales (RDBMS) soportan SQL


y porque el propio Java se ejecuta en la mayora de plataformas,
JDBC permite escribir una aplicacin nica de base de datos que
pueda ejecutarse en diferentes plataformas e interactuar con
diferentes DBMS.

JDBC es similar a ODBC, pero est diseado especficamente para


los programas de Java, mientras que ODBC es independiente del
lenguaje.

JDBC fue desarrollado por JavaSoft, una subsidiaria de Sun


Microsystems.

Ferreiras Aplicaciones JAVA, DB, JDBC 38


Diferentes contextos de una Aplicacin Java JDBC
Aplicacin Java

JDBC Oracle JDBC MySQL ... Otros JDBC

DBMS Oracle DBMS MySQL ... Otros DBMS

Base Base ... Otras Base


de de de
Datos Datos Datos

Ver en http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html

Ferreiras Aplicaciones JAVA, DB, JDBC 39


Una aplicacin Java tiene acceso a la
base de datos a travs de controladores
especficos.

JDBC es la capa que hace que una aplicacin


Java de base de datos sea portable a travs de
diversos SGBD relacionales. As:
Si una aplicacin Java desarrollada con DBMS
Oracle ha de ser portado a otros DBMSs, se
puede hacer sustituyendo el controlador de
Oracle con otro controlador adecuado.

Ferreiras Aplicaciones JAVA, DB, JDBC 40


JDBC helps you to write java applications that manage these three programming activities:

1. Connect to a data source, like a database


2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query

The following simple code fragment gives a simple example of these three steps:

public void connectToAndQueryDatabase(String username, String password)


{

Connection con = DriverManager.getConnection


("jdbc:myDriver:myDatabase", username, password);

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
Mas adelante
float f = rs.getFloat("c");
ejemplos completos
}
// ...

From http://download.oracle.com/javase/tutorial/jdbc/overview/index.html

Ferreiras Aplicaciones JAVA, DB, JDBC 41


Derby Embedded Architecture
When an application accesses a Derby
database using the Embedded Derby JDBC
driver, the Derby engine does not run in a
separate process, and there are no separate
database processes to start up and shut
down.

Instead, the Derby database engine runs


inside the same Java Virtual Machine (JVM) as
the application.

So, Derby becomes part of the application


just like any other jar file that the
application uses.

Fuente http://db.apache.org/derby/papers/DerbyTut/embedded_intro.html

Ferreiras Aplicaciones JAVA, DB, JDBC 42


De un vistazo

Ver SQL clauses, page 74, refDerby SQL


http://www.sql.org/

Ver en http://en.wikipedia.org/wiki/SQL
Ferreiras Aplicaciones JAVA, DB, JDBC 43
SQL
SQL ( del ingles Structured Query
Language), en espaol Lenguaje
Estructurado de Consulta, Es un lenguaje
de programacin diseado para la gestin
de datos en la base de datos relacionales.
Su alcance de aplicacin incluye creacin y
la modificacin esquemas, insertar datos,
consultar, actualizar y eliminar, y el control de
acceso de datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 44


Data types Each column in an SQL table
declares the type (s) that column may
contain. ANSI SQL includes the following
datatypes:
Character strings
CHARACTER(n) or CHAR(n) fixed-width n-character string, padded
with spaces as needed
CHARACTER VARYING(n) or VARCHAR(n) variable-width string with
a maximum size of n characters
NATIONAL CHARACTER(n) or NCHAR(n) fixed width string
supporting an international character set
NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) variable-
width NCHAR string

Ferreiras Aplicaciones JAVA, DB, JDBC 45


Bit strings
BIT(n) an array of n bits
BIT VARYING(n) an array of up to n bits

Numbers

INTEGER and SMALLINT


FLOAT, REAL and DOUBLE PRECISION
NUMERIC(precision, scale) or DECIMAL(precision, scale)

The precision is a positive integer that determines the number of significant digits
in a particular radix (binary or decimal). The scale is a non-negative integer. A
scale of 0 indicates that the number is an integer. For a scale of S, the exact
numeric value is the integer value of the significant digits multiplied by 10-S.
SQL provides a function to round numerics or dates, called TRUNC (in Informix,
DB2, PostgreSQL, Oracle and MySQL) or ROUND (in Informix, Sybase, Oracle,
PostgreSQL and Microsoft SQL Server).
Ferreiras Aplicaciones JAVA, DB, JDBC 46
Date and time

DATE for date values (e.g., 2011-05-03)


TIME for time values (e.g., 15:51:36). The granularity of the time value is
usually a tick (100 nanoseconds).
TIME WITH TIME ZONE or TIMESTAMP the same as TIME, but including
details about the time zone in question.
TIMESTAMP This is a DATE and a TIME put together in one variable
(e.g., 2011-05-03 15:51:36).
TIMESTAMP WITH TIME ZONE or TIMESTAMPTZ the same
as TIMESTAMP, but including details about the time zone in question.

SQL provides several functions for generating a date / time variable out of a
date / time string (TO_DATE, TO_TIME, TO_TIMESTAMP), as well as for
extracting the respective members (seconds, for instance) of such variables.
The current system date / time of the database server can be called by
using functions like NOW.

Ferreiras Aplicaciones JAVA, DB, JDBC 47


Equivalencia de tipos de datos
Java-SQL
Tipo de dato SQL Tipo de dato Java
INTEGER int
SMALLINT short
BIGINT long
BOOLEAN boolean
REAL float
DOUBLE double
FLOAT double
VARCHAR(n) String de longitud variable hasta n
CHAR(n) String de longitud n fija.

Correspondencia entre tipos de datos SQL y tipos de dato Java


Ferreiras Aplicaciones JAVA, DB, JDBC 48
ALTER modifies the structure of an existing object in various ways, for
example, adding a column to an existing table or a constraint, e.g.,:
ALTER TABLE My_table ADD my_field4 NUMBER(3) NOT NULL;
TRUNCATE deletes all data from a table in a very fast way, deleting the data
inside the table and not the table itself. It usually implies a subsequent COMMIT
operation, i.e., it cannot be rolled back.
TRUNCATE TABLE My_table;
DROP deletes an object in the database, usually irretrievably, i.e., it cannot be
rolled back, e.g.,:
DROP TABLE My_table;

Ferreiras Aplicaciones JAVA, DB, JDBC 49


Queries
The most common operation in SQL is the query, which is performed with
the declarative SELECT statement. SELECT retrieves data from one or
more tables, or expressions. Standard SELECT statements have no
persistent effects on the database. Some non-standard implementations of
SELECT can have persistent effects, such as the SELECT INTO syntax
that exists in some databases.
Queries allow the user to describe desired data, leaving the database
management system (DBMS) responsible for planning, optimizing, and
performing the physical operations necessary to produce that result as it
chooses.
A query includes a list of columns to be included in the final result
immediately following the SELECT keyword. An asterisk ("*") can also be
used to specify that the query should return all columns of the queried
tables. SELECT is the most complex statement in SQL, with optional
keywords and clauses that include:

Ferreiras Aplicaciones JAVA, DB, JDBC 50


The FROM clause which indicates the table(s) from which data is to be
retrieved. The FROM clause can include optional JOIN subclauses to specify
the rules for joining tables.
The WHERE clause includes a comparison predicate, which restricts the
rows returned by the query. The WHERE clause eliminates all rows from the
result set for which the comparison predicate does not evaluate to True.
The GROUP BY clause is used to project rows having common values
into a smaller set of rows. GROUP BY is often used in conjunction with SQL
aggregation functions or to eliminate duplicate rows from a result set. The
WHERE clause is applied before the GROUP BY clause.
The HAVING clause includes a predicate used to filter rows resulting from
the GROUP BY clause. Because it acts on the results of the GROUP BY
clause, aggregation functions can be used in the HAVING clause predicate.
The ORDER BY clause identifies which columns are used to sort the
resulting data, and in which direction they should be sorted (options are
ascending or descending). Without an ORDER BY clause, the order of rows
returned by an SQL query is undefined.

Ferreiras Aplicaciones JAVA, DB, JDBC 51


JOIN operations

The JOIN operations, which are among the possible TableExpressions in a


FROM clause, perform joins between two tables. (You can also perform a
join between two tables using an explicit equality test in a WHERE clause,
such as "WHERE t1.col1 = t2.col2".)

Syntax : JOIN Operation

ON specify the join clause by specifying ON with a boolean expression.

Can reference tables not being joined and does not have to reference
either of the tables being joined (though typically it does).

Ferreiras Aplicaciones JAVA, DB, JDBC 52


JOIN operations

Examples

-- Join the EMP_ACT and EMPLOYEE tables


-- select all the columns from the EMP_ACT table and
-- add the employee's surname (LASTNAME) from the EMPLOYEE table
-- to each row of the result

SELECT SAMP.EMP_ACT.*, LASTNAME


FROM SAMP.EMP_ACT JOIN SAMP.EMPLOYEE
ON EMP_ACT.EMPNO = EMPLOYEE.EMPNO

Ferreiras Aplicaciones JAVA, DB, JDBC 53


COUNT(*) function

COUNT(*) is an aggregate function that counts the number of rows


accessed. No NULLs or duplicates are eliminated. COUNT(*) does not
operate on an expression.

Syntax: COUNT(*)

The resulting data type is INTEGER.

Example

-- Count the number of rows in the Flights table

SELECT COUNT(*)
FROM Flights

Ferreiras Aplicaciones JAVA, DB, JDBC 54


The following is an example of a SELECT query
that returns a list of expensive books. The query
retrieves all rows from the Book table in which the
price column contains a value greater than 100.00.
The result is sorted in ascending order by title. The
asterisk (*) in the select list indicates that all
columns of the Book table should be included in
the result set.

SELECT *
FROM Book
WHERE price > 100.00
ORDER BY title;
Ferreiras Aplicaciones JAVA, DB, JDBC 55
The example below demonstrates a query of multiple
tables, grouping, and aggregation, by returning a list of
books and the number of authors associated with each
book.

SELECT Book.title,
COUNT(*) AS Authors
FROM Book JOIN Book_author
ON Book.isbn = Book_author.isbn
GROUP BY Book.title;

Ferreiras Aplicaciones JAVA, DB, JDBC 56


Example output might resemble the following:

Title Authors
------------------------------------ -----------
SQL Examples and Guide 4
The Joy of SQL 1
An Introduction to SQL 2
Pitfalls of SQL 1

Ferreiras Aplicaciones JAVA, DB, JDBC 57


Under the precondition that isbn is the only common column
name of the two tables and that a column named title only
exists in the Books table, the above query could be
rewritten in the following form:

SELECT title,
COUNT(*) AS Authors
FROM Book NATURAL JOIN Book_author
GROUP BY title;

However, many vendors either do not support this


approach, or require certain column naming conventions
in order for natural joins to work effectively.

Ferreiras Aplicaciones JAVA, DB, JDBC 58


SQL includes operators and functions for calculating
values on stored values. SQL allows the use of
expressions in the select list to project data, as in the
following example which returns a list of books that cost
more than 100.00 with an additional sales_tax column
containing a sales tax figure calculated at 6% of the price.

SELECT isbn,
title,
price,
price * 0.06 AS sales_tax
FROM Book
WHERE price > 100.00
ORDER BY title;

Ferreiras Aplicaciones JAVA, DB, JDBC 59


Data manipulation
The Data Manipulation Language (DML) is the subset of
SQL used to add, update and delete data:

INSERT adds rows (formally tuples) to an existing


table, e.g.,:

INSERT INTO My_table


(field1, field2, field3)
VALUES
('test', 'N', NULL);

Ferreiras Aplicaciones JAVA, DB, JDBC 60


UPDATE modifies a set of existing table rows,
e.g.,:
UPDATE My_table
SET field1 = 'updated value'
WHERE field2 = 'N';

DELETE removes existing rows from a


table, e.g.,:
DELETE FROM My_table
WHERE field2 = 'N';

Ferreiras Aplicaciones JAVA, DB, JDBC 61


SQL comments
SQL comments

There are several ways for specifying comments:

line comment. This is indicated by two negative signs (eg. --). The remainder of the text on the line is the comment.
block comment. The start of the block comment is indicated by /*, the end of the comment by */. A block comment can cover text in part of a line, or
can span multiple lines.
rem or @. For Oracle, a line starting with either REM or @ is a comment line.
For many databases, comments are not valid statements. It is expected that the script-processor (in this case AQT) will remove the comments
from the SQL before passing it to the database for processing. Consequently, when running some SQL, AQT will:

remove all line comments from your SQL, except when the Remove Comments option is de-selected (this is discussed later).
not remove any block comments. You should only use block comments with databases that allow these are part of the SQL syntax.
for Oracle, remove all lines starting with rem or @
Remove Comments option

In some circumstances you may want the line comments to remain in your SQL. For instance, you are defining a Stored Procedure and want the
comments to remain as part of the procedure definition.

In this case, go to Options > Run SQL and de-select Remove Comments from SQL. When this option is de-selected, AQT will retain all the line
comments that appear within the body of your SQL statement. Any line comments appearing before the start of your SQL statement will be
removed unless Retain comments before start of SQL is selected.

This option only affects the processing of line comments. Other comments are handled as described earlier.

Beware - if you de-selected this option and include line-comments within normal SQL (such as queries, updates, inserts etc), you may get a syntax
error with some databases.

Ferreiras Aplicaciones JAVA, DB, JDBC 62


Primary Keys
Un primary key, PK, Es una columna o
una combinacin de columnas que
identifican de forma nica una fila en la
tabla, esto es, no podr haber otra fila con
la misma PK en dicha tabla: aparecer
Significa que no puede
en esta columna
un valor repetido
VEHICULOS

ChasisNo (PK) Marca Precio

KW23RO34003456GH TOYOTA 456789.45

PSYUCV9876J34DL34 FIAT 500 856234.12

Ferreiras Aplicaciones JAVA, DB, JDBC 63


Termine de leer el
material de SQL
entregado por el
profesor Ferreiras
y, si le es posible,
busque ms.

Ferreiras Aplicaciones JAVA, DB, JDBC 64


Mapeo de clases a tablas
relacionales
De las clases a las tablas relacionales y de ah a la base de datos relacional:
Mediante un proceso de abstraccin, identificar las clases con sus
atributos que modelarn la realidad del problema que se quiere solucionar
con TOO.
Construir el Diagrama UML de clases mostrando todas las relaciones y
multiplicidades entre ellas.
Para cada clase escribir su notacin UML indicando el o los atributos a
usar como identificador nico <<ID>>
Para cada una de las clases anteriores, escribir su notacin UML de
tabla relacional usando los tipos de datos del DBMS a usar en su
implementacin.

Ferreiras Aplicaciones JAVA, DB, JDBC 65


Mapeo de clases a tablas
relacionales, Ejemplo
1) A partir de la clase dada mas abajo en notacin
UML:
Vehiculo
- chasisNo: String
- marca: String
- precio: double

Ferreiras Aplicaciones JAVA, DB, JDBC 66


Mapeo de clases a tablas
relacionales
2) Escribir la clase identificando el atributo o los atributos ID usando
la notacin de estereotipo de UML.

Identificador nico.
Solo se muestra Vehiculo
las variables que Tambin se puede
- chasisNo: String <<ID>> usar {isID} o,
encapsulan los
- marca: String simplemente, {id}
atributos.
- precio: double Democrticamente,
useremos <<ID>>

Ferreiras Aplicaciones JAVA, DB, JDBC 67


3) Mapear la notacin UML de la clase
anterior a la notacin UML de <<table>>:
Obsrvese:
VEHICULOS
<<table>> El nombre de la clase
chasisNo: CHAR(16) <<PK>> se escribe en
mayscula y en plural.
marca: VARCHAR(10)
precio: DECIMAL(6,2) Los atributos <<ID>
se convierten en <<PK>

El tipo de dato usado


es el del DBMS a usar
... en su implementacin.

Ferreiras Aplicaciones JAVA, DB, JDBC 68


4) Implementar la tabla en la base de datos creada usando el DBMS
seleccionado

CREATE TABLE Vehiculos (


Observe que los tipos de
ChasisNo CHAR(16) PRIMARY KEY, datos SQL se deben
Marca VARCHAR(10), corresponder con el tipo
de informacin que
Precio DECIMAL(6,2) almacenara cada columna
);

Cuando una tabla tiene una PK el SGBD construye un archivo de ndices


que almacena informacin para acceder de manera rpida y efectiva un fila
cuando su PK es conocida.

Ferreiras Aplicaciones JAVA, DB, JDBC 69


Mas ejemplos Clases a Tablas
Relacionales
Ver en el grupo la PPT 15-From class relationships to relational tables

Ferreiras Aplicaciones JAVA, DB, JDBC 70


De un vistazo

Aplicaciones Java
con base de datos

Ferreiras Aplicaciones JAVA, DB, JDBC 71


Aplicaciones con Bases de
Datos
Una aplicacin de base de datos es
un programa computacional utilizado
para la recopilacin, almacenamiento,
manipulacin y recuperacin de
datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 72


Las partes que
componen una Aplicacin

aplicacin con
Controlador ( ODBC,
base de datos son: JDBC, ... )

Servidor de Base de
Datos ( SGBS )

EVIDENTEMENTE,
Aqu hay cosas que Base de Datos
conectar unas con
otras
Ferreiras Aplicaciones JAVA, DB, JDBC 73
Como se organizan estas partes ?
Es establecido por la arquitectura de la
aplicacin. La mas comn es la llamada
arquitectura de Cliente/Servidor.

Ferreiras Aplicaciones JAVA, DB, JDBC 74


En la arquitectura Cliente/Servidor La
aplicacin de base de datos y el SGBD son
separadas en dos partes:

Cliente ( llamado como front-end )

Es la parte que corre (ejecuta) la aplicacin de base


de datos que tiene acceso a la informacin en la base
de datos e interacta con el usuario a travs del teclado,
la pantalla y un dispositivo sealador como un ratn.
Servidor ( llamado como back-end )

Es la parte que ejecuta el SGBD y se ocupa de las


funciones requeridas para el acceso compartido y
simultneo de los datos en la base de datos.
Ferreiras Aplicaciones JAVA, DB, JDBC 75
Donde se ejecutan el cliente y el servidor?
En la Arquitectura Cliente/Servidor El cliente ( la
aplicacin de base de datos ) y el servidor ( el
SGBD ) pueden:
Correr en un mismo computador
(arquitectura cliente / servidor de un nivel ); O,

Correr en diferentes computadores


conectados a travs de una red (arquitectura
cliente / servidor de n-niveles) .
En la asignatura INF-329, "Anlisis y Diseo de
Sistemas", su profesor deber desarrollar con toda la
profundidad debida la arquitectura Cliente/Servidor.

Ferreiras Aplicaciones JAVA, DB, JDBC 76


Grficamente
Arquitectura Cliente / Servidor de un nivel
(1-Tier Client-Server Architecture )

Un nivel y tres capas. Contiene la


aplicacin con la capa de presentacin, la
capa de negocio y la capa de datos. Todo en
una maquina. La capa de datos contiene el
SGBD que funciona como servidor a la capa
de negocio (cliente) que intercambia con la
capa de presentacin. La capa de negocio
contiene el cdigo que se conecta va el
JDBC con el servidor de datos o SGBD.

Ferreiras Aplicaciones JAVA, DB, JDBC 77


Grficamente
Arquitectura Cliente / Servidor de dos niveles
(2-Tier Client-Server Architecture )

Servidor
Contiene el Cliente Contiene la
SGBD y la aplicacin
base de datos con la capa
fsica ( las de
tablas ) presentacin
y la capa de
negocio.
Conecta va
el JDBC con
el SGBD

Ferreiras Aplicaciones JAVA, DB, JDBC 78


En la arquitectura cliente/servidor de
dos niveles ( 2-Tiers ) Hay una aplicacin
ejecutndose en la maquina cliente la cual
interacta con el servidor de base datos.
Tpicamente, el nivel cliente contiene la
capa de presentacin (GUI), la capa de
negocio (reglas de negocio) y la capa de
acceso a la base de datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 79


Grficamente
Arquitectura Cliente / Servidor de tres niveles
(3-Tier Client-Server Architecture )

Servidor Servidor nivel medio Contiene la


Cliente capa de
presentacin
(GUI).

Contiene la capa de negocio


Contiene el (reglas de negocio) y el cdigo
SGBD y la base de acceso al SGBD va el JDBC.
de datos fsica (
las tablas )
Ferreiras Aplicaciones JAVA, DB, JDBC 80
En la arquitectura de 3-niveles, tambin
conocida como arquitectura multinivel, hay 3
o mas niveles interactuando, cada uno con
sus responsabilidades propias especificas:
Nivel 1: Contiene la capa de presentacin (GUI) incluyendo controles
simples y validacin de entradas de usuarios.

Nivel 2: Tambin conocido como servidor de aplicacin, provee la


lgica de los procesos de negocio (reglas de negocio) y el acceso a los
datos va el JDBC.
Nivel 3: Contiene el servidor de base de datos y la base de datos
misma.

Ferreiras Aplicaciones JAVA, DB, JDBC 81


Algunas de las ventajas de la
arquitectura de 3-niveles son:
Es mas fcil reemplazar las capas en cualquier nivel,
incluso el nivel mismo, sin afectar los otros niveles;
Con la separacin de la aplicacin de la funcionalidad
de la base de datos se obtiene un mejor equilibrio de la
carga.

En el nivel 2, el servidor de aplicacin, se pueden


hacer cumplir polticas de seguridad adecuadas sin
afectar a los clientes

Ferreiras Aplicaciones JAVA, DB, JDBC 82


Java y SQL

Entre SQL y Java no existe ninguna


relacin. Simplemente, son
lenguajes diferentes. No obstante,
podemos utilizar Java para enviar
comandos SQL a una base de
datos.

Ferreiras Aplicaciones JAVA, DB, JDBC 83


Java y SQL
A diferencia de Java, SQL no es sensible a las
maysculas. Sin embargo, como una cuestin de
convencin, vamos a utilizar estos ltimos en
maysculas para las palabras reservadas de SQL
y en maysculas y minsculas para los nombres
de tablas y columnas (notacin camellada) . SQL
usa comillas simples, no usa comillas dobles, para
delimitar las cadenas.

Ferreiras Aplicaciones JAVA, DB, JDBC 84


Java y SQL
En las aplicaciones orientadas a objetos la
informacin se almacena como estados de los
objetos. En las bases de datos relacionales como
filas de tablas. Por tanto, para almacenar la
informacin tratada en un programa orientado a
objetos en una base de datos relacional es
necesaria un mapeo de las clases de los objetos
que requieren persistencia hacia tablas
relacionales.

Ferreiras Aplicaciones JAVA, DB, JDBC 85


Java y SQL
Para mapear clases a tablas relacionales debemos tener en cuenta lo
siguiente:

Los mtodos de las clases no pueden ser almacenados directamente, o


ejecutados automticamente, en una base de dato relacional;

Las relaciones entre las clases son representadas en una base de datos
relacional usando integridad referencial (FK)

Las cosas, los conceptos dentro de un sistema pueden ser modelados


usando un Modelo de Datos Entidad-Relacion ( es la base para el esquema
relacional ), o, usando un diagrama de clases ( la base del modeo OO ) o
ambos.

Ferreiras Aplicaciones JAVA, DB, JDBC 86


Java y SQL
Entre los dos modelos antes indicados hay
considerables coincidencias :
Agrupamiento de los elementos de datos en entidades o
clases;

Definicin, entre las entidades o entre las clases, de


relaciones uno-a-uno, uno-a-mucho y mucho-a-mucho.
Estas coincidencias proveen una base para
representar clase y estado de sus objetos dentro
de una base relacional de datos. Veamos:

Ferreiras Aplicaciones JAVA, DB, JDBC 87


Java y SQL

Aplicacin OO BD Relacional
Clase Tabla
Atributos Campos o Columnas
Estado de un objeto Fila o tuplas
Identificador nico Clave primaria (PK)
Puntero o referencia a otro Clave fornea (FK)
objeto

Donde Significa mapeo a

Ferreiras Aplicaciones JAVA, DB, JDBC 88


Equivalencia entre tipos de datos
Java-SQL
Tipo de dato SQL Tipo de dato Java
INTEGER int
SMALLINT short
BIGINT long
BOOLEAN boolean
REAL float
DOUBLE double
FLOAT double
VARCHAR(n) String de longitud variable hasta n
CHAR(n) String de longitud n fija.

Correspondencia entre tipos de datos SQL y tipos de dato Java


Ferreiras Aplicaciones JAVA, DB, JDBC 89
java.sql API
* Interfaces
* Classes * Exceptions
Array
Blob BatchUpdateException
CallableStatement Date DataTruncation
Clob DriverManager SQLClientInfoException
Connection SQLDataException
DriverPropertyInfo SQLException
DatabaseMetaData
Driver SQLPermission SQLFeatureNotSupportedException
NClob Time SQLIntegrityConstraintViolationException
ParameterMetaData SQLInvalidAuthorizationSpecException
Timestamp SQLNonTransientConnectionException
PreparedStatement
Ref Types SQLNonTransientException
ResultSet SQLRecoverableException
ResultSetMetaData SQLSyntaxErrorException
* Enums SQLTimeoutException
RowId
Savepoint SQLTransactionRollbackException
SQLData ClientInfoStatus SQLTransientConnectionException
SQLInput SQLTransientException
PseudoColumnUsage SQLWarning
SQLOutput
SQLXML RowIdLifetime
Statement
Struct
Wrapper

http://download.oracle.com/javase/7/docs/api/

Ferreiras Aplicaciones JAVA, DB, JDBC 90


Usando Derby, Java DB
Para los objetivos de este nivel
introductorio de aplicaciones Java con base
de datos el profesor Ferreiras trabaja con
un DBMS ligero que viene embebido en la
JVM, este es Derby o JavaDB. Ver toda la
documentacin en:
http://db.apache.org/derby/index.html

Ferreiras Aplicaciones JAVA, DB, JDBC 91


EJEMPLOS

En el grupo estn los ejemplos en los


archivos:
...

Ferreiras Aplicaciones JAVA, DB, JDBC 92


EJERCICIOS

...

Ferreiras Aplicaciones JAVA, DB, JDBC 93


GRACIAS.

Ferreiras Aplicaciones JAVA, DB, JDBC 94

Вам также может понравиться