BASE DE DATOS.

Slides:



Advertisements
Presentaciones similares
FUNDAMENTALS OF THE JAVA PROGRAMMING LANGUAGE
Advertisements

Acceso a Bases de Datos con Java
Tema 3 J2EE Java Database Connectivity Temas Selectos de Cómputo Grupo 912.
ARCHIVOS Y CONEXIÓN A BASE DE DATOS. FileInputStream: Clase que representa ficheros de texto accedidos en orden secuencial, byte a byte. FileWriter: Clase.
Tecnología de la Información Ing. Diego J. Arcusin BASES DE DATOS / SQL.
UNITA - IBARRA TRIGGERS
IBD CLASE 15. SQL Lenguaje de Consultas Estruturado (SQL) ◦Lenguaje de trabajo estándard para modelo relacional ◦Componentes ◦DDL: Data Definition Language.
Fernando Alonso Nicolás Serrano Acceso a Bases de Datos con Java JDBC 01 de Abril de 2008.
Programación Orientada a Objetos Modulo 7 JDBC Universidad de Chile Departamento de Ciencias de la Computación.
Notes #18 Numbers 31 and higher Standard 1.2
How to Conjugate Regular –AR – Er - IR Verbs in the Present Tense.
1 Programación Interactiva JDBC Escuela de Ingeniería de Sistemas y Computación Facultad de Ingeniería Universidad del Valle.
INSTRUCCIONES Elaboración de la Presentación:
LENGUAJE SQL.
LENGUAJE ESTRUCTURADO DE CONSULTAS
Prof. De Bases de Datos: Lcdo. Luis Peña. El lenguaje más habitual para construir las consultas a bases de datos relacionales es SQL, Structured Query.
 La sentencia SELECT recupera todas las columnas o un subconjunto de ellas de una tabla. Esto afecta a todas las filas de la tabla, a menos que especifiquemos.
Consultas SQL. SQL SQL es un lenguaje de consulta estructurado (Structured Query Languague). Se utiliza para: Eliminar Modificar Consultar La base de.
JDBC. Definición Java Database Conectivity El acceso a bases de datos JDBC implica abrir una conexión ejecutar comandos SQL en un sentencia procesar los.
SQL Lenguaje Estructurado de Consultas. Structured Query Lenguaje (SQL). Lenguaje de acceso a bases de datos. Proyecto de Investigación de IBM. La mayoria.
Un juego de adivinanzas: ¿Dónde está el tesoro? A1B1C1D1E1F1 A4B4C4D4E4F4 A2B2C2D2E2F2 A5B5C5D5E5F5 A3B3C3D3E3F3 A6B6C6D6E6F6 Inténtalo de nuevo Inténtalo.
Unidad 6. Tema 4. Lenguaje de consultas SQL
Forming Questions ¡Aprenda! Forming Questions By Patricia Carl October 2013.
Sentencias DDL y DML PostgreSQL. Base de Datos I – Fundamentos Básicos PostgreSQL PostgreSQL es un servidor de base de datos relacional libre bajo la.
Structure Query Languaje SQL. Introducción a SQL El lenguaje de consulta estructurado (SQL) es un lenguaje de base de datos normalizado, utilizado por.
Querys a bases de datos con MS ACCESS. DEFINAMOS LOS TERMINOS: DML=Lenguaje de manipulación de datos Las sentencias DML permiten generar consultas para.
DML Transact SQL Sesión X Triggers. Duración 2 Horas.
6 Triggers ORACLE - III Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega Bases de datos II I-2014 Universidad del Cauca Ing. Wilson Ortega.
Selección Condicionada de Filas Uso de la cláusula WHERE La cláusula WHERE restringe las columnas que retorna una consulta según la condición que se imponga.
COMANDOS SQL. ¿QUÉ ES SQL? El lenguaje de consulta estructurado es un lenguaje declarativo que permite la creación, acceso e interacción de bases de datos.
Francisco Moreno Bases de Datos II Universidad Nacional
EQUILIBRIUM OF A PARTICLE IN 2-D Today’s Objectives: Students will be able to : a) Draw a free body diagram (FBD), and, b) Apply equations of equilibrium.
SQL: Structured Query Language
Lenguaje de manipulación de datos
MYSQL SQL: Lenguaje de consulta estructurado. Es un lenguaje de programación para trabajar con BD relacionadas, entre las cuales tenemos MYSQL, ORACLE,
Tipos de datos en MYSQL YEAR: Año. “YYYY” o “YY”
BASE DE DATOS IUPSM CLASE PRACTICA. PROF. ING. JOSE L GUZMAN H.
Notes #20 Notes #20 There are three basic ways to ask questions in Spanish. Can you guess what they are by looking at the photos and photo captions on.
Programación Orientada a Objetos
Español 3 24 de febrero de 2017.
Técnicas y Herramientas de Computación
Gustar V. Encantar.
Structure Query Languaje
SQL: structured Query Language
UN DISPARADOR O TRIGGER es un procedimiento que se ejecuta cuando se cumple una condición establecida al realizar una operación. Es una rutina autónoma.
PREGUNTAS: Questions and Question Words
SQL Lenguaje de Consulta Estructurado
Base de Datos II Almacenamiento.
Getting to know you more!
First Grade Dual High Frequency Words
Lenguaje de Manipulación de Datos
Lenguaje SQL Contenidos Que es SQL ? Estructura de SQL
Structure Query Languaje
Base de Datos II 2da Parte. Propiedad ACID  La propiedad ACIDa es una carácterística de un DBMS para poder compartir datos en forma segura.  A :
Name:_______________________________ Group: _______________________________ Date: _______________________________ Teacher: ______________________________.
PREGUNTAS: Questions and Question Words
Recetas 3 Objetivo: Hacer preguntas Hablar sobre la comida
Quasimodo: Tienes que hacer parte D de la tarea..
Telling time in Spanish
Modificación de datos. Introducción Uso de transacciones Inserción de datos Eliminación de datos Actualización de datos Consideraciones acerca del rendimiento.
The Windows File System and Windows Explorer To move around the file system and examine your files or get to one you want (say, to modify, delete or copy.
Indirect Questions First Day on the Job 11 Focus on Grammar 4 Part X, Unit 28 By Ruth Luman, Gabriele Steiner, and BJ Wells Copyright © Pearson Education,
Java Database Connectivity JDBC
Capítulo 7 USO DE BASES DE DATOS OBJETO- RELACIONALES.
Los adjetivos demostrativos Notes #16 What is a demonstrative adjective in English? Demonstrative adjectives in English are simply the words: THISTHESE.
Development of the concert programme
Welcome to PowerPoint gdskcgdskfcbskjc. Designer helps you get your point across PowerPoint Designer suggests professional designs for your presentation,
Fundamentos de las Base de Datos. Contenido Que es una Base de Datos. La diferencia entre datos e informacion. Clasificacion de las base de datos. Importancia.
Globalization Politics and the preservation of nation state.
Las Preguntas (the questions) Tengo una pregunta… Sí, Juan habla mucho con el profesor en clase. No, Juan no habla mucho en clase. s vo s vo Forming.
Transcripción de la presentación:

BASE DE DATOS

Sumario Capitulo 5: BASE DE DATOS Introducción a base de datos   Introducción a base de datos Introducción a SQL Ejemplo de conexión con Bases de Datos Propietarias (SQL SERVER) Ejemplo de conexión con Bases de Datos de Libre Distribución (MySql, Posgresql)

Introducción a SQL

CONSULTAS SQL cristiansalazar@uach.cl

¿Qué es SQL? Lenguaje de consulta estructurado (SQL: Structured Query Languague) . Es un lenguaje de base de datos normalizado. Utilizado para consultar, modificar o eliminar datos en una Base de Datos.

Componentes Comandos Claúsulas Operadores Funciones

Comandos Existen 2 tipos: DLL (definición de datos): Permiten crear y definir nuevas bases de datos, campos e índices. CREATE DROP ALTER DML (manipulación de datos): Permiten generar consultas para ordenar, filtrar y extraer datos. SELECT INSERT UPDATE DELETE

Cláusulas FROM WHERE GROUP BY HAVING ORDER BY

Operadores Lógicos: Comparación: <, >, <>, <=, >= AND OR NOT Comparación: <, >, <>, <=, >=

Funciones COUNT SUM MAX MIN AVG

Consulta básica SELECT A FROM B Donde A son los datos que requiero (columnas) y B es de donde obtengo esos datos.

Ejemplo SELECT nombre, apellidos, edad FROM estudiantes

WHERE A veces NO se necesitan obtener datos tan generales, y es cuando se aplican filtros, con la clausula WHERE. SELECT A FROM B WHERE C Donde C, es una o más condiciones.

Ejemplo SELECT nombres, apellidos, edad FROM estudiantes WHERE edad > 21

Alias Los alias son un nombre de asignación que se le dan a los recursos, en este caso las tablas. Luego se pueden llamar a sus atributos desde ese alias, continuados con un punto (“.”) .

Ejemplo SELECT c.nombres, f.nombres FROM campus c, funcionarios f WHERE c.id_campus = f.id_campus

Alias 2 Es posible dar un alias (nombre) al titulo de las columnas de una tabla, que no es el mismo que posee en la Base de Datos. Ejemplo sin Alias: Select l.titulo, l.agno From libros l TITULO AGNO Matemáticas 2007 Lenguaje y Comunicaciones 1998 Cs. Biológicas 2003

Ejemplo con Alias Select l.titulo, l.agno As AÑO From libros l TITULO Matemáticas 2007 Lenguaje y Comunicaciones 1998 Cs. Biológicas 2003

GROUP BY La cláusula GROUP BY se usa para generar valores de agregado para cada fila del conjunto de resultados. Cuando se usan sin una cláusula GROUP BY, las funciones de agregado sólo devuelven un valor de agregado para una instrucción SELECT. Ejemplo: SELECT nombre_columna1, nombre_columna2 FROM nombre_tabla GROUP BY nombre_columna1

GROUP BY: Ejemplo RESULTADO CONSULTA Valdivia 1800 Temuco 250 tienda_info nombre_tienda ventas fecha Valdivia 1500 05-jan-2010 Temuco 250 07-jan-2010 300 08-jan-2010 Osorno 700 RESULTADO Valdivia 1800 Temuco 250 Osorno 700 CONSULTA SELECT nombre_tienda, SUM(ventas) FROM tienda_info GROUP BY nombre_tienda

HAVING Especifica una condición de búsqueda para un grupo o agregado. HAVING sólo se puede utilizar con la instrucción SELECT. Normalmente, HAVING se utiliza en una cláusula GROUP BY. Cuando no se utiliza GROUP BY, HAVING se comporta como una cláusula WHERE. Ejemplo: SELECT nombre_columna1, SUM(nombre_columna2) FROM nombre_tabla [ GROUP BY nombre_columna1 ] HAVING (condición de función aritmética)

HAVING: Ejemplo CONSULTA RESULTADO tienda_info nombre_tienda ventas fecha Valdivia 1500 05-jan-2010 Temuco 250 07-jan-2010 300 08-jan-2010 Osorno 700 CONSULTA SELECT nombre_tienda, SUM(ventas) FROM tienda_info GROUP BY nombre_tienda HAVING SUM(ventas) > 1500 RESULTADO Valdivia 1800

ORDER BY Especifica el orden utilizado en las columnas devueltas en una instrucción SELECT. La cláusula ORDER BY no es válida en vistas, funciones insertadas, tablas derivadas ni subconsultas. Ejemplo: SELECT nombre_columna1, nombre_columna2 FROM nombre_tabla [ WHERE condicion] ORDER BY nombre_columna1 [ASC, DESC]

ORDER BY: Ejemplo RESULTADO CONSULTA Valdivia 1500 05-jan-2010 tienda_info nombre_tienda ventas fecha Valdivia 1500 05-jan-2010 Temuco 250 07-jan-2010 300 08-jan-2010 Osorno 700 RESULTADO Valdivia 1500 05-jan-2010 Osorno 700 08-jan-2010 Valdivia 300 08-jan-2010 Temuco 250 07-jan-2010 CONSULTA SELECT nombre_tienda, ventas, fecha FROM tienda_info ORDER BY ventas DESC

OPERADORES LOGICOS (AND-OR) C1 OR C2 V F C1 C2 C1 AND C2 V F

OPERADORES LOGICOS: Ejemplo AND tienda_info nombre_tienda ventas fecha Valdivia 1500 05-jan-2010 Temuco 250 07-jan-2010 300 08-jan-2010 Osorno 700 CONSULTA SELECT * FROM tienda_info WHERE ventas > 500 AND nombre_tienda = ‘Valdivia’ RESULTADO Valdivia 1500 05-jan-2010

OPERADORES LOGICOS: Ejemplo OR tienda_info nombre_tienda ventas fecha Valdivia 1500 05-jan-2010 Temuco 250 07-jan-2010 300 08-jan-2010 Osorno 700 CONSULTA SELECT * FROM tienda_info WHERE ventas > 500 OR nombre_tienda = ‘Valdivia’ RESULTADO Valdivia 1500 05-jan-2010 Valdivia 300 08-jan-2010 Osorno 700 08-jan-2010

Modelo de Datos Para este laboratorio usaremos la Base de Datos Biblioteca desarrollado en la clase anterior. Para ello use la imagen que se encuentra en siveduc, “Biblioteca.png” y cargue el archivo “Biblioteca.sql” en PLSQL como se enseño en la clase anterior.

Actualizaciones a la Base de datos El lenguaje SQL puede ser usado para consultar la base de datos como también para modificar los datos. Tres comandos SQL para modificar el contenido de las tablas en la base de datos: Insert – Agrega nuevas filas de datos a una tabla Delete – Elimina filas de datos de una tabla Update – Modifica los datos existentes en una tabla.

INSERT INSERT INTO Nombretabla [ (listaDeColumnas) ] VALUES (listaDeValores) listaDeColumnas es opcional; si se omite, SQL asume la lista de todas las columnas en el orden original. todas las columnas omitidas en la lista deben haber sido declaradas NULL cuando la tabla fue creada, a menos que se haya utilizado la opción DEFAULT cuando se creo la columna.

INSERT La listaDeValores debe coincidir con listaDeColumnas como sigue: El número de ítems de cada lista debe ser el mismo Debe haber una correspondencia directa en la posición de los ítems en las dos listas, El tipo de datos de cada item en listaDeValores debe ser compatible con el tipo de datos de la correspondiente columna.

Ejemplo 5.34 INSERT . . . VALUES Tabla Empleado Insertar una nueva fila en la tabla Empleado, entregando los datos para todas las columnas:

Ejemplo 5.34 INSERT . . . VALUES INSERT INTO Empleado Insertar una nueva fila en la tabla Empleado, entregando los datos para todas las columnas: Tabla Empleado Como estamos insertando datos en cada columna en el orden en que la tabla fue creada, no hay necesidad de especificar una lista de columnas. Note que el carácter literal tal como ‘Alan’ debe ir encerrado en comillas simples. INSERT INTO Empleado VALUES (‘SG16’, ‘Alan’, ‘Brown’, ‘Asistente’, ‘M’, Date‘1957-05- 25’, 83000, ‘B003’);

Ejemplo 5.35 INSERT usando valores por defecto Insertar una nueva fila en la tabla Empleado suministrando datos para todas las columnas obligatorias. numEmpleado, nombre, apellido, cargo, salario y numOficina. INSERT INTO Empleado (numEmpleado, nombre, apellido, cargo, salario, numOficina) VALUES (‘SG44’, ‘Amme’, ‘Jones’, ‘Asistente’, 8100, ‘B003’); O INSERT INTO Empleado VALUES (‘SG44’, ‘Anne’, ‘Jones’, ‘Asistente’, NULL, NULL, 8100, ‘B003’);

INSERT … SELECT La segunda forma de la instrucción INSERT permite que múltiples filas sean copiadas de una o más tablas a otra, y tiene el siguiente formato: INSERT INTO NombreTabla [ (listaDeColumnas) ] SELECT ...

Ejemplo 5.35 INSERT … SELECT Asuma que hay una tabla EmpleadoTotalPropiedad, que contiene los nombres de los empleados y el número de propiedades que ellos manejan: EmpleadoTotalPropiedad (numEmpleado, Nombre, Apellido, totalProp) Poblar la tabla EmpleadoTotalPropiedad usando los detalles de la tabla Empleado y la tabla Propiedad.

Ejemplo 5.35 INSERT … SELECT Tabla Propiedad Tabla Empleado Poblar la tabla EmpleadoTotalPropiedad usando los detalles de la tabla Empleado y la tabla Propiedad. EmpleadoTotalPropiedad (numEmpleado, Nombre, Apellido, totalProp)

Ejemplo 5.35 INSERT … SELECT INSERT INTO EmpleadoTotalPropiedad (SELECT e.numEmpleado, Nombre, Apellido, COUNT(*) FROM Empleado e, Propiedad p WHERE e.numEmpleado = p.numEmpleado Group BY e.numempleado , nombre, apellido) UNION (SELECT numEmpleado, nombre, apellido, 0 FROM Empleado e WHERE NOT EXIST (SELECT * FROM Propiedad p WHERE e.numEmpleado = p.numEmpleado)); Este ejemplo es complejo porque deseamos contar el número de propiedades que el empleado maneja. Si omitimos la segunda parte de la UNION obtenemos la lista de aquellos empleados que manejan al menos una propiedad; en otras palabras, excluimos aquellos empleados que actualmente no manejan propiedades. Por lo tanto para incluir aquellos empleados que no manejan propiedades , necesitamos usar la instrucción UNION e incluir un segundo SELECT para agregar tales empleados, usando 0 para el atributo total. Note que algunos dialectos de SQL pueden no permitir el uso del operador UNION dentro de un subselect para un INSERT

Ejemplo 5.35 INSERT … SELECT Tabla resultado Ejemplo 5.35 Si la segunda parte de la UNIÓN se omite, excluye a los empleados que no manejan actualmente ninguna propiedad.

UPDATE UPDATE NombreTabla SET columnName1 = dataValue1 [, columnName2 = dataValue2...] [WHERE searchCondition] NombreTabla puede ser el nombre de una tabla base o una vista actualizable. La cláusula SET especifica los nombres de una o más columnas a ser actualizadas

UPDATE La cláusula WHERE es opcional: Si se omite, las columnas nombradas serán actualizadas para todas las filas en tabla; Si se especifica, solamente esas filas que satisfacen la searchCondition son actualizadas. El(los) nuevo(s) dataValue(s) debe(n) ser compatible con el tipo de datos para la columna correspondiente.

Ejemplo 5.38/39 UPDATE todas las filas Tabla Empleado Dé a todos los Empleados un aumento de sueldo del 3%. Dé a todos los Gerentes un aumento de sueldo del 5%.

Ejemplo 5.38/39 UPDATE todas las filas Tabla Empleado Dé a todos los Empleados un aumento de sueldo del 3%. UPDATE Empleado SET salario = salario*1.03;

Ejemplo 5.38/39 UPDATE todas las filas Tabla Empleado Dé a todos los Gerentes un aumento de sueldo del 5%. UPDATE Empleado SET salario = salario*1.05 WHERE cargo = ‘Gerente’;

Ejemplo 5.38/39 UPDATE múltiples columnas Promueva a David Ford (numEmpleado=‘SG14’) a Gerente y cambie su salario a 190.000.

Ejemplo 5.38/39 UPDATE múltiples columnas Promueva a David Ford (numEmpleado=‘SG14’) a Gerente y cambie su salario a 190.000. UPDATE Empleado SET cargo = ‘Gerente’, salario = 190000 WHERE numEmpleado = ‘SG14’;

DELETE NombreTabla puede ser una tabla base o una vista actualizable. DELETE FROM NombreTabla [WHERE searchCondition] NombreTabla puede ser una tabla base o una vista actualizable. searchCondition es opcional; si se omite, todas las filas son eliminadas de la tabla. Este no elimina la tabla. Si se especifica search_condition solamente se eliminan aquellas filar que satisfacen la condición

Ejemplo 5.41/42 DELETE Filas especificas Tabla Visita Suprima todas las visitas que se relacionen con la propiedad PG4. Elimine todos los registros de la tabla Visita.

Ejemplo 5.41/42 DELETE Filas especificas Tabla Visita Suprima todas las visitas que se relacionen con la propiedad PG4. DELETE FROM Visita WHERE numPropiedad = ‘PG4’;

Ejemplo 5.41/42 DELETE Filas especificas Tabla Visita Elimine todos los registros de la tabla Visita. DELETE FROM Visita;

1) How to get the database connection? There are two ways to get the database connection. 1) First is to load the the Driver using Class.forName() and use the DriverManager.getConnection(). 2) Second is to use the DataSource to get the connection.

Getting the connection from DriverManager: Loading the driver: Class.forName("DriverName"); e.g.Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); Getting the connection from DriverManager: Connection connection = DriverManager.getConnection( "jdbc:microsoft:sqlserver://127.0.0.1\\ABCD:1443;” + “DatabaseName=JDBCDB","username", "password"); Getting the connection from the DataSource: To make the data source we need to deploy the *-ds.xml file in the deploy directory of JBoss Application Server. You can find the sample *-ds.xml files for different databases in the jboss-eap-4.3/jboss-as/docs/examples/jca directory.

Sample *-ds.xml files for postgresql database : <datasources> <local-tx-datasource> <use-java-context>false</use-java-context> <jndi-name>PostgresDS</jndi-name> <connection-url>jdbc:postgresql://127.0.0.1:5432/ejb3db</connection-url> <!—- For ssl connection <connection- url>jdbc:postgresql://127.0.0.1:5432/ejb3db?ssl=true&sslfactory=org.postg resql.ssl.NonValidatingFactory&</connection-url> --> <driver-class>org.postgresql.Driver</driver-class> <user-name>x</user-name> <password>y</password> <!-- sql to call when connection is created. Can be anything, select 1 is valid for PostgreSQL <new-connection-sql>select 1</new-connection-sql> --> <!--pooling parameters--> <min-pool-size>50</min-pool-size> <max-pool-size>80</max-pool-size> <blocking-timeout-millis>5000</blocking-timeout-millis> <idle-timeout-minutes>1</idle-timeout-minutes> <!-- sql to call on an existing pooled connection when it is obtained from pool. Can be anything, select 1 is valid for PostgreSQL <check-valid-connection-sql>select 1</check-valid-connection-sql> --> <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml --> <metadata> <type-mapping>PostgreSQL 8.0</type-mapping> </metadata> </local-tx-datasource> </datasources> Sample *-ds.xml files for postgresql database :

How to get Connection from the database? InitialContext initialContext = new InitialContext(); DataSource dataSource = (DataSource) initialContext.lookup("PostgresDS"); Connection connection = dataSource.getConnection() jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=127.0.0.1:1099

2) Setting up Tables: Creating a Table: Creating JDBC Statements: String createTableCoffees = "CREATE TABLE COFFEES" + " (COF_NAM VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT," + " SALES INTEGER, TOTAL INTEGER)"; Creating JDBC Statements: executeQuery() is used for select statements (DQL). executeUpdate() is used to create or modify tables (DDL and DML). Statement statement = connection.createStatement(); statement.executeUpdate(createTableCoffees);

Executing Statements: executeQuery("SELECT statement...") executeUpdate("DDL and DML statements...") Entering Data into a Table: Statement statement = connection.createStatement(); statement.executeUpdate( "INSERT INTO COFFEES " + "VALUES('Colombian', 101, 7.99, 0, 0"); Getting Data from a Table: ResultSet resultSet = statement.executeQuery( "SELECT * FROM COFFEES");

3) Updating Tables: String query = "SELECT COF_NAME, SALES FROM COFFEES “ + " WHERE COF_NAME LIKE 'Colombian'"; ResultSet resultSet = statement.executeQuery(query); while(rs.next()){ String s = resultSet.getString("COF_NAME"); int n = resultSet.getInt("SALES"); System.out.println(n + " ponds of " + s + " sold this week."); } String updateString = "UPDATE COFFEES " + "SET TOTAL = TOTAL + 75 " + "WHERE COF_NAME LIKE 'Colombian'"; statement.executeUpdate(updateString); String query = "SELECT COF_NAME, TOTAL FROM COFFEES" + "WHERE COF_NAME LIKE 'Colombian'"; ResultSet resultSet = statment.executeQuery(query); while(rs.next()) { String s = rs.getString(1); int n = rs.getInt(2); System.out.println(n + " ponds of " + s + " sold till date."); }

4) Using PreparedStatement: When to use PreparedStatment? If you want to execute a Statement Object many times, it will normally reduce execution time to use a PreparedStatement object instead. The main feature of a PreparedStatement object is that, unlike a Statement object it is given an SQL statement when it is created. The advantage of this is that in most cases, the SQL statement will be sent to the DBMS right away, where it will be compiled. As a result the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatemen’s SQL statement without having to compile it first. Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statements and supply it with different values each time you execute it.

Creating a PreparedStatement Object: PreparedStatement updateSales = connection.preparedStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME" + " LIKE ? "); Supplying values for PreparedStatement Parameters: Code Fragment I: String updateString = "UPDATE COFFEES SET SALES=75 " + " WHERE COF_NAME LIKE 'Colombian'"; statement.executeUpdate(updateString); Code Fragment II: PreparedStatement updateSales = connection.preparedStatement( "UPDATE COFFEES SET SALES=? " + "WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate();

Using a loop to set values: Note: Once a parameter has been set with a value, it will retain that value until it is reset to another value or the method clearParameters is called. updateSales.setInt(1, 100); updateSales.setString(2, "French_Roast"); updateSales.executeUpdate(); updateSales.setString(2, "Espresso"); updateSales.executeUpdate(); Using a loop to set values: PreparedStatement updateSales; String updateString = "update COFFEES "+ " set SALES = ? where COF_NAME like ?"; updateSales = con.preparedStatement(updateString); int [] salesForWeek = {175, 150, 60, 155, 90}; String [] coffees = ("Colombian", "French_Roast", "Colombian_Decaf", "French_Roast_Decaf"); int len = coffees.length; for(int i=0; I < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); }

Return values for the method executeUpdate: * executeQuery returns a ResultSet object containing the results of the query sent to the DBMS, the return value for executeUpdate is an int that indicates how many rows of a table were updated. updateSales.setInt(1, 50); updateSales.setString(2, "Espresso"); int n = updateSales.executeUpdate(); // n = 1 because one row had a change in it. When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 0. int n = executeUpdate(createTableCoffees); // n = 0 Note that when the return value for executeUpdate is 0, it can mean one of two things: 1) the statement executed was an update statement that affected zero rows, or 2) the statement executed was a DDL statement.

5) Using Joins: String createSUPPLIERS = "create table SUPPLIERS " + "(SUP_ID INTEGER, SUP_NAME VARCHAR(40), " + "STREET VARCHAR(40), CITY VARCHAR(20), " + "STATE CHAR(2), ZIP CHAR(5))"; statement.executeUpdate(createSUPPLIERS); statement.executeUpdate("insert int SUPPLIER values (101, " + "'Acme, Inc.', '99 Market Street', 'Groundsville', " + "'CA', '95199'"); statement.executeUpdate("insert int SUPPLIERS values (49, " + "'Superior Coffee', '1 Party Place', 'Mendocino', 'CA' " +"'95460'"); statement.executeUpdate("Insert into SUPPLIERS value(150, " + "'The High Ground', '100 Coffee Lane', 'Meadows', 'CA‘, '93966'"; ResultSet rs = statement.executeQuery("select * from SUPPLIERS"); String query = "SELECT COFFEES.COF_NAME " + "FROM COFFEES, SUPPLIERS " + "WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' " + "and SUPPLIER_ID = COFFEES.SUP_ID"; ResultSet rs = statement.executeQuery(query); System.out.println("Coffees bought from Acme, Inc.: "); while(rs.next()) { String coffeeName = rs.getString("COF_NAME"); System.out.println(" " + coffeeName); }

6) Using Transactions: Disabling Auto-Commit Mode A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed or none of the statements is executed. Disabling Auto-Commit Mode connection.setAutoCommit(false); where connection is an active connection. Committing a Transaction Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. connection.setAutoCommit(false); PreparedStatement updateSales = connection.preparedStatment( "UPDATE COFFEES SET TOTAL = TOTAL + " + " ? WHERE COF_NAME LIKE ?"); updateTotal.setInt(1, 50); updateTotal.setString(2, "Colombian"); updateTotal.executeUpdate(); connection.commit(); connnection.setAutoCommit(true);

Using Transaction to Preserve Data Integrity Transaction isolation levels 1) int TRANSACTION_NONE = 0; 2) int TRANSACTION_READ_UNCOMMITTED = 1; 3) int TRANSACTION_READ_COMMITTED = 2; 4) int TRANSACTION_REPEATABLE_READ = 4; 5) int TRANSACTION_SERIALIZABLE = 8; void setTransactionIsolation(int level) throws SQLException; int getTransactionIsolation() throws SQLException; When to call method rollback? If you are trying to execute one or more statements in a transaction and get an SQLException, you should call the method rollback to abort the transaction and start the transaction all over again.

7) Using Stored Procedures: In SQL Create procedure SHOW_SUPPLIERS As Select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME from SUPPLIERS, COFFEES where SUPPLIERS.SUP_ID = COFFEES.SUP_ID Order by SUP_NAME In Java (JDBC) String createProcedure = “Create procedure SHOW_SUPPLIERS” + “as “ + “select SUPPLIER.SUP_NAME, COFFEES.COF_NAME ” + “from SUPPLIERS, COFFEES ” + “where SUPPLIER.SUP_ID = COFFEES.SUP_ID ” + “order by SUP_NAME”; Statement stmt = con.createStatement(); Stmt.executeUpdate(createProcedure);

8) Creating Complete JDBC Applications: Steps Putting code in a class definition. Importing classes to make them visible import java.sql.*; Using the main method. Using try and catch blocks. Retrieving Exceptions.

try { - - - } catch (SQLException ex) { System.err.println(“SQLException: ” + ex.getMessage()); } try { Class.forName(“myDriverClassName”); } catch (ClassNotFoundException ex) { System.err.println(“ClassNotFoundException: ” + ex.getMessage()); }

Catching Exceptions try { - - - } catch (SQLException ex) { System.err.println(“SQLException Caught”); while(ex != null){ System.out.println(“Message: “ + ex.getMessage()); System.out.println(“SQLState: “ + ex.getSQLState()); System.out.println(“ErrorCode: “ + ex.getErrorCode()); ex = ex.getNextException(); System.out.println(“ ”); }

Retrieving Warnings SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a # a connection object # a statement object (including PreparedStatment and CallableStatement objects) # a ResultSet object Each of these classes have a getWarnings method, which you mush invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from the previous statement, so they do not build up. This means, however that if you want to retrieve warnings reported on a statement you must do so before you execute another statement.

Example Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( “Select COF_NAME from COFFEES”); while(rs.next) { String CoffeName = rs.getString(“COF_NAME”); System.out.println(“ Coffees available at the Coffee Break: ”); System.out.println(“ ” + coffeeName); SQLWarning warning = stmt.getWarnings(); if(warning != null) { System.out.println(“—Warning-”); while(warning != null){ System.out.println(“Message: ” + warning.getMessage()); System.out.println(“SQLState: ” + warning.getSQLState()); System.out.println(“Vendor Eror Code: ” + warning.getErrorCode()); warning = warning.getNextWarning(); } ---

--- SQLWarning warn = rs.getWarnings(); if(warning != null) { System.out.println(“-- Warning --”); while(warn != null) { System.out.println(“Message: ” + warn.getMessage()); System.out.println(“SQLState: ” + warn.getSQLState()); System.out.println(“Vendor Error Code:” + warn.getErrorCode()); warn = warn.getNextWarning(); }

Ejemplos

Ejemplo 1

Ejemplo 2

Ejemplo 3

Ejemplo 4

Cargar Driver

Conección

Crear Tabla

Insertar Registro

Actualizando

Seleccionando Registro

Seleccionando Registro (2)

Borrar Registro

Ejemplo de CRUD

Insertar Registro

Actualizar

Obtener Listado

Eliminar Registro

Ejercicio 1 Elabore una aplicación que vierta los datos del fichero (resultante del proyecto del interciclo anterior) y verterlos a una tabla de la base de datos Ejercicio 2 Implemente una interface IRepoPersona con los métodos necesarios para gestionar los datos de una persona e implemente una clase que permita gestionar dichos datos si estos están almacenados en Bases de datos.