Presentation is loading. Please wait.

Presentation is loading. Please wait.

Capítulo 23: Conectividad a Bases de Datos con JDBC

Similar presentations


Presentation on theme: "Capítulo 23: Conectividad a Bases de Datos con JDBC"— Presentation transcript:

1 Capítulo 23: Conectividad a Bases de Datos con JDBC
TM Resumen Introducción Modelo Relaciona de Bases de Datos Generalidades de las Bases de Datos Relacionales: La Base de datos libros SQL Consulta Básica SELECT La Cláusula WHERE La Cláusula ORDER BY Cómo fusionar varias tablas: INNER JOIN La instrucción INSERT La Instrucción UPDATE La Instrucción DELETE Creación de la base de datos libros en MySQL Manipulación de Bases de Datos con JDBC Conectando y consultanto una base de datos Consultas a la base de datos libros

2 23.1 Introducción Base de datos DBMS SQL Colección organizada de datos
Las mas popurales son las bases de datos relacionales DBMS Sistema Manejador de Bases de Datos (Database management system ) Almacena y organiza los datos SQL Bases de datos relacionales Lenguaje de consulta estructurado (Structured Query Language)

3 23.1 Introducción (Cont.) RDBMS JDBC
Sistema Manejador de Base de Datos Relacionales SQL Server, Oracle, Sybase, DB”, Infromix, MySQL JDBC Conectividad a Bases de Datos de Java JDBC driver (controlador) , implementa una interfaz en los programas java para conectarse a diversas bases de datos.

4 23.2 Modelo de Bases de Datos Relacionales
Base de datos Relacional Tabla Filas, columnas Llave Primaria Identificador único de los datos Comandos SQL Consultas (Queries)

5 23.2 Modelo de Bases de Datos Relacionales (Cont.)
Numero Nombre Departamento Salario Ubicacion 23603 Jones 413 1100 New Jersey 24568 Kerwin 413 2000 New Jersey Fila 34589 Larson 642 1800 Los Angeles 35761 Myers 611 1400 Orlando 47132 Neumann 413 9000 New Jersey 78321 Stephens 611 8500 Orlando Llave Primaria Columna Fig Datos de ejemplo para la tabla Empleado

6 23.2 Modelo de Bases de Datos Relacionales (Cont.)
Departamento Ubicacion 413 New Jersey 611 Orlando 642 Los Angeles Fig Resultado de seleccionar datos distintos de Departamento y Ubicacion de la tabla Empleado

7 23.3 Generalidades de las bases de datos relacionales: La Base de datos libros
Cuatro tablas autores, editoriales, isbnAutor y titulos Relaciones de las tablas

8 23.3 Generalidades de las bases de datos relacionales: La Base de datos libros (Cont.)

9 23.3 Generalidades de las bases de datos relacionales: La Base de datos libros (Cont.)
idEditorial nombreEditorial 1 Prentice Hall 2 Prentice Hall PTG Fig. 23.6 Datos de la tabla editoriales

10 23.3 Generalidades de las bases de datos relacionales: La Base de datos libros (Cont.)

11 23.3 Generalidades de las bases de datos relacionales: La Base de datos libros (Cont.)

12 23.3 Generalidades de las bases de datos relacionales: La Base de datos libros (Cont.)
idAutor isbn 1 2 3 4 Fig Datos de ejemplo de la tabla isbnAutor .

13 23.3 Relational Database Overview: The books Database (Cont.)
autores idAutor nombrePila apellidoPaterno isbnAutor idAutor isbn titulos isbn titulo numeroEdicion copyright idEditorial archivoimagen precio 1 8 1 8 8 editoriales idEditorial nombreEditorial 1 Fig Relaciones de tablas en la base de datos libros

14 SQL descripción general SQL palabras clave (keywords)
SQL keyword Descripción SELECT Recupera datos de una o mas tablas FROM Tablas involucradas en cada consulta, se requiere para cada . WHERE Criterios de selección que determinan cuales filas se van a Recuperar, borrar o actualizar GROUP BY Criterios para agrupar filas ORDER BY Criterios para ordenar filas INNER JOIN Fusionar filas de varias tablas INSERT Insertar filas en una tabla especificada UPDATE Actualizar filas en una tabla especificada DELETE Eliminar filas en una tabla especificada Fig SQL palabras clave para consultas

15 23.4.1 Consulta Básica SELECT
SELECT * FROM nombreTabla SELECT * FROM autores Recuperar ciertas columnas de la tabla

16 Especificar criterio de selcción
Cláusula WHERE Especificar criterio de selcción SELECT columna1, columna2, … FROM NombreTabla WHERE criterio SELECT titulo, numeroEdicion, copyright FROM titulos WHERE copyright > 2000 Operadores de condición en la cláusula WHERE <, >, <=, >=, =, <> LIKE Caracteres comodines % y _

17 Cláusula WHERE (Cont.)

18 Cláusula WHERE(Cont.)

19 WHERE Clause (Cont.)

20 Cláusula ORDER BY opcional
Clausula ORDER BY Cláusula ORDER BY opcional SELECT columna1, columna2, … FROM nombreTabla ORDER BY columna ASC SELECT columna1, columna2, … FROM nombreTabla ORDER BY columna DESC ORDER BY campos múltiples ORDER BY columna1 tipoOrden, columna2 tipoOrden, … Combinar WHERE y ORDER BY

21 23.4.3 Cláusula ORDER BY (Cont.)

22 23.4.3 Cláusula ORDER BY (Cont.)

23 23.4.3 Cláusula ORDER BY (Cont.)

24 23.4.3 Cláusula ORDER BY (Cont.)

25 23.4.4 Fusionar datos de varias tablas
Los datos se guardan en tablas separadas para evitar redundacia. Debido a esto a veces es necesario fusionar datos de varias tablas en una sola consulta

26 23.4.4 Fusionar datos de varias tablas(Cont.)

27 Inserta una fila dentro de una tabla
La instrucción INSERT Inserta una fila dentro de una tabla INSERT INTO nombreTabla ( columna1, … , columnaN ) VALUES ( valor1, … , valorN ) INSERT INTO autores ( nombrePila, apellidoPaterno) VALUES ( ‘Sue’, ‘Smith’ ) idAutor nombrePila apellidoPaterno 1 Harvey Deitel 2 Paul 3 Tem Nieto 4 Sean Santry 5 Sue Smith Fig Datos en la tabla autores, después del INSERT

28 Modicar datos de una tabla
La instrucción UPDATE Modicar datos de una tabla UPDATE nombreTabla SET columna1 = valor1, … , columnaN = valorN WHERE criterios UPDATE autores SET apellidoPaterno = ‘Jones’ WHERE apellidoPaterno = ‘Smith’ AND nombrePila = ‘Sue’ authorID firstName lastName 1 Harvey Deitel 2 Paul 3 Tem Nieto 4 Sean Santry 5 Sue Jones Fig Datos en tabla autores después de UPDATE

29 Elimina datos de una tabla
La instrucción DELETE Elimina datos de una tabla DELETE FROM nombreTabla WHERE criterios DELETE FROM autores WHERE apellidoPaterno = ‘Jones’ AND nombrePila = ‘Sue’ authorID firstName lastName 1 Harvey Deitel 2 Paul 3 Tem Nieto 4 Sean Santry Fig Datos tabla autores después de DELETE

30 23.5 Creando Base de Datos libros en MySQL
Fig Executing Cloudscape from a command prompt in Windows 2000.

31 23.6 Manipulando Bases de Datos con JDBC
Conectarse a una Base de Datos Consultar una Base de Datos Desplegar los resultados de la consulta

32 23.6.1 Conectándose y consultando una base de datos
MostrarAutores Muestra el contenido completo de la base de datos autores Despliega el contenido de la tabla en un objeto JTextArea Ver Ejercicio MostrarAutores

33 23.6.1 Conectándose y consultando una base de datos (Cont.)
Type Description 1 The JDBC - to ODBC bridge driver connects Java programs to Microsoft ODBC (Open Database Connectivity) data sources. The Java 2 Software Development Kit from Sun Microsystems, Inc. includes the JDBC ( sun.jdbc.odbc.Jd bc OdbcDriver ). This driver typically requires the ODBC driver to be installed on the client computer and normally requires configuration of the ODBC data source. The bridge driver was introduced primarily for development purposes and should not be used fo r production applications. 2 Native API, partly Java drivers enable JDBC programs to use database specific APIs (normally written in C or C++) that allow client programs to access databases via the Java Native Interface. This driver type translates JDBC i nto database specific code. Type 2 drivers were introduced for reasons similar to the Type 1 ODBC bridge driver. 3 Net pure Java drivers take JDBC requests and translate them into a network protocol that is not database specific. These requests are s ent to a server, which translates the database requests into a database specific protocol. 4 protocol pure Java drivers convert JDBC requests to database network protocols, so that Java programs can connect directly to a database. Fig. 2 3.26 JDBC driver types.

34 23.6.2 Querying the books Database
Allow the user to enter any query into the program Display the results of a query in a JTable

35 1 // Fig. 23.27: ResultSetTableModel.java
// A TableModel that supplies ResultSet data to a JTable. 3 import java.sql.*; import java.util.*; import javax.swing.table.*; 7 // ResultSet rows and columns are counted from 1 and JTable // rows and columns are counted from 0. When processing 10 // ResultSet rows or columns for use in a JTable, it is 11 // necessary to add 1 to the row or column number to manipulate 12 // the appropriate ResultSet column (i.e., JTable column 0 is 13 // ResultSet column 1 and JTable row 0 is ResultSet row 1). 14 public class ResultSetTableModel extends AbstractTableModel { private Connection connection; private Statement statement; private ResultSet resultSet; private ResultSetMetaData metaData; private int numberOfRows; 20 // keep track of database connection status private boolean connectedToDatabase = false; 23 ResultSetTableModel enables a Jtable to display the contents of a ResultSet.

36 Establishes a connection to the database.
// initialize resultSet and obtain its meta data object; // determine number of rows public ResultSetTableModel( String driver, String url, String query ) throws SQLException, ClassNotFoundException { // load database driver class Class.forName( driver ); 31 // connect to database connection = DriverManager.getConnection( url ); 34 // create Statement to query database statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY ); 39 // update database connection status connectedToDatabase = true; 42 // set query and execute it setQuery( query ); } 46 ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Line 33 Lines Line 44 Establishes a connection to the database. Invokes Connection method createStatement to create a Statement object. Invokes ResultSetTableModel method setQuery to perform the default query.

37 Obtains the fully qualified class name for the specified column.
// get class that represents column type public Class getColumnClass( int column ) throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); 53 // determine Java class of column try { String className = metaData.getColumnClassName( column + 1 ); 57 // return Class object that represents className return Class.forName( className ); } 61 // catch SQLExceptions and ClassNotFoundExceptions catch ( Exception exception ) { exception.printStackTrace(); } 66 // if problems occur above, assume type Object return Object.class; } 70 ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Line 56 Line 59 Line 68 Obtains the fully qualified class name for the specified column. Loads the class definition for the class and returns the corresponding Class object. Returns the default type.

38 Obtains the number of columns in the ResultSet.
// get number of columns in ResultSet public int getColumnCount() throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); 77 // determine number of columns try { return metaData.getColumnCount(); } 82 // catch SQLExceptions and print error message catch ( SQLException sqlException ) { sqlException.printStackTrace(); } 87 // if problems occur above, return 0 for number of columns return 0; } 91 // get name of a particular column in ResultSet public String getColumnName( int column ) throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Line 80 Obtains the number of columns in the ResultSet.

39 Obtains the column name from the ResultSet.
98 // determine column name try { return metaData.getColumnName( column + 1 ); } 103 // catch SQLExceptions and print error message catch ( SQLException sqlException ) { sqlException.printStackTrace(); } 108 // if problems, return empty string for column name return ""; } 112 // return number of rows in ResultSet public int getRowCount() throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); 119 return numberOfRows; } 122 Obtains the column name from the ResultSet. ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Line 101

40 123 // obtain value in particular row and column
public Object getValueAt( int row, int column ) throws IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); 130 // obtain a value at specified ResultSet row and column try { resultSet.absolute( row + 1 ); 134 return resultSet.getObject( column + 1 ); } 137 // catch SQLExceptions and print error message catch ( SQLException sqlException ) { sqlException.printStackTrace(); } 142 // if problems, return empty string object return ""; } 146 ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Line 133 Line 135 Uses ResultSet method absolute to position the ResultSet cursor at a specific row. Uses ResultSet method getObject to obtain the Object in a specific column of the current row.

41 Executes the query to obtain a new ResultSet.
// set new database query string public void setQuery( String query ) throws SQLException, IllegalStateException { // ensure database connection is available if ( !connectedToDatabase ) throw new IllegalStateException( "Not Connected to Database" ); 154 // specify query and execute it resultSet = statement.executeQuery( query ); 157 // obtain meta data for ResultSet metaData = resultSet.getMetaData(); 160 // determine number of rows in ResultSet resultSet.last(); // move to last row numberOfRows = resultSet.getRow(); // get row number 164 // notify JTable that model has changed fireTableStructureChanged(); } 168 ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Line 156 Line 162 Line 163 Line 166 Executes the query to obtain a new ResultSet. Uses ResultSet method last to position the ResultSet cursor at the last row in the ResultSet. Uses ResultSet method getRow to obtain the row number for the current row in the ResultSet. Invokes method fireTableStructureChanged to notify any JTable using this ResultSetTableModel object as its model that the structure of the model has changed.

42 169 // close Statement and Connection
public void disconnectFromDatabase() { // close Statement and Connection try { statement.close(); connection.close(); } 177 // catch SQLExceptions and print error message catch ( SQLException sqlException ) { sqlException.printStackTrace(); } 182 // update database connection status finally { connectedToDatabase = false; } } 188 189 } // end class ResultSetTableModel ResultSetTableModel enables a Jtable to display the contents of a ResultSet. Lines Close the Statement and Connection if a ResultSetTableModel object is garbage collected.

43 23.6.2 Querying the books Database (Cont.)

44 23.6.2 Querying the books Database (Cont.)

45 DisplayQueryResults for querying database books. Lines 15, 16, 19
// Fig : DisplayQueryResults.java // Display the contents of the Authors table in the // Books database. 4 import java.awt.*; import java.awt.event.*; import java.sql.*; import java.util.*; import javax.swing.*; 10 import javax.swing.table.*; 11 12 public class DisplayQueryResults extends JFrame { 13 // JDBC driver and database URL static final String JDBC_DRIVER = "com.ibm.db2j.jdbc.DB2jDriver"; static final String DATABASE_URL = "jdbc:db2j:books"; 17 // default query selects all rows from authors table static final String DEFAULT_QUERY = "SELECT * FROM authors"; 20 private ResultSetTableModel tableModel; private JTextArea queryArea; 23 // create ResultSetTableModel and GUI public DisplayQueryResults() { super( "Displaying Query Results" ); DisplayQueryResults for querying database books. Lines 15, 16, 19 Define the database driver class name, database URL and default query.

46 DisplayQueryResults for querying database books. Lines 36-37
28 // create ResultSetTableModel and display database table try { 31 // specify location of database on filesystem System.setProperty( "db2j.system.home", "C:/Cloudscape_5.0" ); 34 // create TableModel for results of query SELECT * FROM authors tableModel = new ResultSetTableModel( JDBC_DRIVER, DATABASE_URL, DEFAULT_QUERY ); 38 // set up JTextArea in which user types queries queryArea = new JTextArea( DEFAULT_QUERY, 3, 100 ); queryArea.setWrapStyleWord( true ); queryArea.setLineWrap( true ); 43 JScrollPane scrollPane = new JScrollPane( queryArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); 47 // set up JButton for submitting queries JButton submitButton = new JButton( "Submit Query" ); 50 // create Box to manage placement of queryArea and // submitButton in GUI Box box = Box.createHorizontalBox(); box.add( scrollPane ); box.add( submitButton ); 56 DisplayQueryResults for querying database books. Lines 36-37 Create TableModel for results of query SELECT * FROM authors

47 Create JTable delegate for tableModel
JTable resultTable = new JTable( tableModel ); 59 // place GUI components on content pane Container c = getContentPane(); c.add( box, BorderLayout.NORTH ); c.add( new JScrollPane( resultTable ), BorderLayout.CENTER ); 64 // create event listener for submitButton submitButton.addActionListener( 67 new ActionListener() { 69 // pass query to table model public void actionPerformed( ActionEvent event ) { // perform a new query try { tableModel.setQuery( queryArea.getText() ); } 77 // catch SQLExceptions when performing a new query catch ( SQLException sqlException ) { JOptionPane.showMessageDialog( null, sqlException.getMessage(), "Database error", JOptionPane.ERROR_MESSAGE ); 83 Create JTable delegate for tableModel DisplayQueryResults for querying database books. Line 58 Lines Line 75 Register an event handler for the submitButton that the user clicks to submit a query to the database. Invokes ResultSetTableModel method setQuery to execute the new query.

48 DisplayQueryResults for querying database books.
// try to recover from invalid user query // by executing default query try { tableModel.setQuery( DEFAULT_QUERY ); queryArea.setText( DEFAULT_QUERY ); } 90 // catch SQLException when performing default query catch ( SQLException sqlException2 ) { JOptionPane.showMessageDialog( null, sqlException2.getMessage(), "Database error", JOptionPane.ERROR_MESSAGE ); 96 // ensure database connection is closed tableModel.disconnectFromDatabase(); 99 System.exit( 1 ); // terminate application 101 } // end inner catch 103 } // end outer catch 105 } // end actionPerformed 107 } // end ActionListener inner class 109 ); // end call to addActionListener 111 DisplayQueryResults for querying database books.

49 DisplayQueryResults for querying database books.
// set window size and display window setSize( 500, 250 ); setVisible( true ); 115 } // end try 117 // catch ClassNotFoundException thrown by // ResultSetTableModel if database driver not found catch ( ClassNotFoundException classNotFound ) { JOptionPane.showMessageDialog( null, "Cloudscape driver not found", "Driver not found", JOptionPane.ERROR_MESSAGE ); 124 System.exit( 1 ); // terminate application } // end catch 127 // catch SQLException thrown by ResultSetTableModel // if problems occur while setting up database // connection and querying database catch ( SQLException sqlException ) { JOptionPane.showMessageDialog( null, sqlException.getMessage(), "Database error", JOptionPane.ERROR_MESSAGE ); 134 // ensure database connection is closed tableModel.disconnectFromDatabase(); 137 System.exit( 1 ); // terminate application } 140 DisplayQueryResults for querying database books.

50 DisplayQueryResults for querying database books.
// dispose of window when user quits application (this overrides // the default of HIDE_ON_CLOSE) setDefaultCloseOperation( DISPOSE_ON_CLOSE ); 144 // ensure database connection is closed when user quits application addWindowListener( 147 new WindowAdapter() { 149 // disconnect from database and exit when window has closed public void windowClosed( WindowEvent event ) { tableModel.disconnectFromDatabase(); System.exit( 0 ); } } ); 158 } // end DisplayQueryResults constructor 160 // execute application public static void main( String args[] ) { new DisplayQueryResults(); } 166 167 } // end class DisplayQueryResults DisplayQueryResults for querying database books.

51 DisplayQueryResults for querying database books. Program output

52 Interface CallableStatement
23.7 Stored Procedures Stored procedures Store SQL statements in a database Invoke SQL statements by programs accessing the database Interface CallableStatement Receive arguments Output parameters

53 23.8 Internet and World Wide Web Resources
Sun Microsystems JDBC home page Java.sun.com/products/jdbc SQL materials Cloudscape database home page


Download ppt "Capítulo 23: Conectividad a Bases de Datos con JDBC"

Similar presentations


Ads by Google