Professional Documents
Culture Documents
Aplicaciones Java Con Base de Datos Relacional: V8.0 Octubre 2015 Ferreiras
Aplicaciones Java Con Base de Datos Relacional: V8.0 Octubre 2015 Ferreiras
Ferreiras
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
Coooomo ?!!
Pero aun no
hemos dado la
asignatura Base
de Dato I
No os
preocupis, el
seor guiar
sus ovejas
Ferreiras
De un vistazo
Conceptos Bsicos
de Bases de Datos
Ferreiras
Data
The word data covers the collection of facts stored in the database;
Determining what data to enter into the database and how to organize those data is a vital part
of the database designers job.
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.
Data
Data concept.
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:
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
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.
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:
10
Datos
Los datos consisten de hechos en bruto,
tales como:
10008889112
Rafael
20
Pimentel
fp@yahoo.com
1345.67
11
Ferreiras
primerNombre
Rafael
primerApellido
Pimentel
correoElectronico
rf@uasd.com
creditos
20
12
totalPagar
1345.56
filas
(tuplas)
columnas
Ferreiras
13
nombre
apellido
pena
100000045
TOYOTA
PEREZ
20
100045678
PERCIO
CIVIC
13
100005678
LUIS
CANOSO
30
100001333
MARIA
CUQUITA
22
Ferreiras
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
15
Ferreiras
16
Ferreiras
17
archivo de personal
archivo de Ventas
Registros
archivo de nomina
Archivos
Jose Perez
545.23
2.3
25
2348.33
4.5
Campos
Registros
Campos
Caracteres
Ferreiras
545.23
2.3
Caracteres
01010000
Bits, ASCII STD 8 de la P
Aplicaciones JAVA, DB, JDBC
18
Ferreiras
19
20
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
22
De un vistazo
Servidor de Base da datos
o SGBD
Ferreiras
23
Ferreiras
24
Ferreiras
25
Ferreiras
26
Ferreiras
27
sistema de base de
datos que esta
embebido (integrado)
en la JVM
Ferreiras
28
Ferreiras
29
De un vistazo
Accesando a bases de
datos
Ferreiras
30
31
controlador
Base
de
Datos
SGBD
Conecta la
aplicacin con la
base de datos a
travs del SGBD
Ferreiras
32
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
33
...
Ferreiras
34
De un vistazo
JDBC
[ Java DataBase Connectivity ]
Ferreiras
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
36
Ferreiras
37
38
JDBC Oracle
JDBC MySQL
DBMS Oracle
DBMS MySQL
Base
de
Datos
Base
de
Datos
Ver en http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html
Ferreiras
39
Ferreiras
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:
41
Fuente http://db.apache.org/derby/papers/DerbyTut/embedded_intro.html
Ferreiras
42
De un vistazo
SQL
http://www.sql.org/
Ver en http://en.wikipedia.org/wiki/SQL
Ferreiras
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
44
NATIONAL CHARACTER
VARYING(n)
or 45
NVARCHAR(n) variable-width NCHAR string
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
46
Ferreiras
47
INTEGER
int
SMALLINT
short
BIGINT
long
BOOLEAN
boolean
REAL
float
DOUBLE
double
FLOAT
double
VARCHAR(n)
CHAR(n)
48
Ferreiras
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 nonstandard 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,
Ferreiras
Aplicaciones JAVA, DB, JDBC
and performing the
physical operations50
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
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
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
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
54
55
ON Book.isbn = Book_author.isbn
GROUP BY Book.title;
Ferreiras
56
Authors
------------------------------------
-----------
An Introduction to SQL
Pitfalls of SQL
Ferreiras
57
Ferreiras
58
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
60
Ferreiras
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
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
Significa que no puede
la misma PK en dicha tabla: aparecer
en esta columna un
valor repetido
VEHICULOS
ChasisNo (PK)
Marca
Precio
KW23RO34003456GH
TOYOTA
456789.45
PSYUCV9876J34DL34
FIAT 500
856234.12
Ferreiras
63
Termine de leer el
material de SQL
entregado por el
profesor Ferreiras
y, si le es posible,
busque ms.
Ferreiras
64
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
65
Ferreiras
66
Solo se muestra
las variables que
encapsulan los
atributos.
Vehiculo
Identificador nico.
- marca: String
Tambin se puede
usar {isID} o,
simplemente, {id}
- precio: double
Democrticamente,
useremos <<ID>>
Ferreiras
67
Obsrvese:
El nombre de la clase
se escribe en
mayscula y en plural.
...
Ferreiras
68
);
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
69
Ferreiras
70
De un vistazo
Aplicaciones Java
con base de datos
Ferreiras
71
Ferreiras
72
Aplicacin
Controlador ( ODBC,
JDBC, ... )
Servidor de Base de
Datos ( SGBS )
EVIDENTEMENTE,
Aqu hay cosas que
conectar unas con
otras
Ferreiras
Base de Datos
73
Ferreiras
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
75
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
77
Grficamente
Arquitectura Cliente / Servidor de dos niveles
(2-Tier Client-Server Architecture )
Servidor
Contiene el
SGBD y la
base de datos
fsica ( las
tablas )
Ferreiras
Cliente
Contiene la
aplicacin
con la capa
de
presentacin
y la capa de
negocio.
Conecta va
el JDBC con
el SGBD
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
79
Grficamente
Arquitectura Cliente / Servidor de tres niveles
(3-Tier Client-Server Architecture )
Servidor
Contiene el
SGBD y la base
de datos fsica (
las tablas )
Ferreiras
Cliente
Contiene la
capa de
presentacin
(GUI).
80
En la arquitectura de 3-niveles,
tambin conocida como arquitectura
multinivel, hay 3 o mas niveles
interactuando, cada uno con sus
responsabilidades
especificas:
Nivel 1: Contiene la capa de propias
presentacin (GUI)
incluyendo controles
simples y validacin de entradas de usuarios.
Ferreiras
81
Ferreiras
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
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
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
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
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.
87
Java y SQL
Aplicacin OO
BD Relacional
Clase
Tabla
Atributos
Campos o Columnas
Estado de un objeto
Fila o tuplas
Identificador nico
Puntero o referencia a otro
objeto
88
INTEGER
int
SMALLINT
short
BIGINT
long
BOOLEAN
boolean
REAL
float
DOUBLE
double
FLOAT
double
VARCHAR(n)
CHAR(n)
89
java.sql API
* Interfaces
Array
Blob
CallableStatement
Clob
Connection
DatabaseMetaData
Driver
NClob
ParameterMetaData
PreparedStatement
Ref
ResultSet
ResultSetMetaData
RowId
Savepoint
SQLData
SQLInput
SQLOutput
SQLXML
Statement
Struct
Wrapper
* Exceptions
* Classes
Date
DriverManager
DriverPropertyInfo
SQLPermission
Time
Timestamp
Types
* Enums
ClientInfoStatus
PseudoColumnUsage
RowIdLifetime
BatchUpdateException
DataTruncation
SQLClientInfoException
SQLDataException
SQLException
SQLFeatureNotSupportedException
SQLIntegrityConstraintViolationException
SQLInvalidAuthorizationSpecException
SQLNonTransientConnectionException
SQLNonTransientException
SQLRecoverableException
SQLSyntaxErrorException
SQLTimeoutException
SQLTransactionRollbackException
SQLTransientConnectionException
SQLTransientException
SQLWarning
http://download.oracle.com/javase/7/docs/api/
Ferreiras
90
Ferreiras
91
EJEMPLOS
Ferreiras
92
EJERCICIOS
...
Ferreiras
93
GRACIAS.
Ferreiras
94