Presentation is loading. Please wait.

Presentation is loading. Please wait.

12 Accessing Databases with JDBC.

Similar presentations


Presentation on theme: "12 Accessing Databases with JDBC."— Presentation transcript:

1 12 Accessing Databases with JDBC

2 OBJECTIVES Relational database concepts.
In this chapter you will learn: Relational database concepts. To use Structured Query Language (SQL) to retrieve data from and manipulate data in a database. To use the JDBC™ API of package java.sql to access databases. To use the RowSet interface from package javax.sql to manipulate databases. To use JDBC 4.0’s automatic JDBC driver discovery. To use PreparedStatements to create precompiled SQL statements with parameters. How transaction processing makes database applications more robust.

3 25.1 Introduction 25.2 Relational Databases 25.3 Relational Database Overview: The books Database 25.4 SQL Basic SELECT Query WHERE Claus ORDER BY Claus Merging Data from Multiple Tables: INNER JOIN INSERT Statement UPDATE Statement DELETE Statement 25.5 Instructions for installing MySQL and MySQL Connector/J

4 25.6 Instructions for Setting Up a MySQL User Account
25.7 Creating Database book in MySQL 25.8 Manipulating Databases with JDBC Connecting to and Querying a Database Querying the books Database 25.9 RowSet Interface Java DB/Apache Derby PreparedStatements Stored Procedures Transaction Processing Wrap-Up Web Resources and Recommended Readings

5 25.1 Introduction Database DBMS SQL Collection of data
Database management system Storing and organizing data SQL Relational database Structured Query Language

6 25.1 Introduction (Cont.) RDBMS JDBC
Relational database management system MySQL Open source Available for both Windows and Linux dev.mysql.com/downloads/mysql/4.0.hml JDBC Java Database Connectivity JDBC driver Enable Java applications to connect to database Enable programmers to manipulate databases using JDBC

7 Software Engineering Observation 25.1
Using the JDBC API enables developers to change the underlying DBMS without modifying the Java code that accesses the database.

8 25.2 Relational Databases Relational database SQL queries Table
Rows, columns Primary key Unique data SQL queries Specify which data to select from a table

9 Fig. 25.1 | Employee table sample data.

10 Fig. 25.2 | Result of selecting distinct Department and Location data from table Employee.

11 25.3 Relational Database Overview: The books Database
Sample books database Four tables authors authorID, firstName, lastName titles isbn, title, editionNumber, copyright, publisherID, imageFile, price authorISBN authorID, isbn

12 Fig. 25.3 | authors table from the books database.

13 Fig. 25.4 | Sample data from the authors table.

14 25.3 Relational Database Overview: The books Database (Cont.)
Foreign key A column matches the primary key column in another table Helps maintain the Rule of Referential Integrity Every foreign key value must appear as another table’s primary key value

15 Fig. 25.5 | authorISBN table from the books database.

16 Fig. 25.6 | Sample data from the authorISBN table of books.

17 Fig. 25.7 | titles table from the books database.

18 Fig. 25.8 | Sample data from the titles table of the books database.

19 25.3 Relational Database Overview: The books Database (Cont.)
Entity-relationship (ER) diagram Tables in the database Relationships among tables Rule of Entity Integrity Primary key uniquely identifies each row Every row must have a value for every column of the primary key Value of the primary key must be unique in the table

20 Fig. 25.9 | Table relationships in the books database.

21 Common Programming Error 25.1
Not providing a value for every column in a primary key breaks the Rule of Entity Integrity and causes the DBMS to report an error.

22 Common Programming Error 25.2
Providing the same value for the primary key in multiple rows causes the DBMS to report an error.

23 Common Programming Error 25.3
Providing a foreign-key value that does not appear as a primary-key value in another table breaks the Rule of Referential Integrity and causes the DBMS to report an error.

24 25.4 SQL SQL keywords SQL queries and statements

25 Fig. 25.10 | SQL query keywords.

26 25.4.1 Basic SELECT Query Simplest format of a SELECT query
SELECT * FROM tableName SELECT * FROM authors Select specific fields from a table SELECT authorID, lastName FROM authors

27 Fig. 25.11 | Sample authorID and lastName data from the authors table.

28 Software Engineering Observation 25.2
For most queries, the asterisk (*) should not be used to specify column names. In general, you process results by knowing in advance the order of the columns in the result—for example, selecting authorID and lastName from table authors ensures that the columns will appear in the result with authorID as the first column and lastName as the second column. Programs typically process result columns by specifying the column number in the result (starting from number 1 for the first column). Selecting columns by name also avoids returning unneeded columns and protects against changes in the actual order of the columns in the table(s).

29 Common Programming Error 25.4
If you assume that the columns are always returned in the same order from a query that uses the asterisk (*), the program may process the results incorrectly. If the column order in the table(s) changes or if additional columns are added at a later time, the order of the columns in the result would change accordingly.

30 25.4.2 WHERE Clause specify the selection criteria
SELECT columnName1, columnName2, … FROM tableName WHERE criteria SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2002

31 Portability Tip 25.1 See the documentation for your database system to determine whether SQL is case sensitive on your system and to determine the syntax for SQL keywords (i.e., should they be all uppercase letters, all lowercase letters or some combination of the two?).

32 Fig. 25.12 | Sampling of titles with copyrights after 2005 from table titles.

33 25.4.2 WHERE Clause (Cont.) WHERE clause condition operators
<, >, <=, >=, =, <> LIKE wildcard characters % and _ SELECT authorID, firstName, lastName FROM authors WHERE lastName LIKE ‘D%’

34 Fig. 25.13 | Authors whose last name starts with D from the authors table.

35 Portability Tip 25.2 Read your database system’s documentation carefully to determine whether your system supports the LIKE operator. The SQL we discuss is supported by most RDBMSs, but it is always a good idea to check the features of SQL that are supported by your RDBMS.

36 25.4.2 WHERE Clause (Cont.) SELECT authorID, firstName, lastName
FROM authors WHERE lastName LIKE ‘_i%’

37 Fig. 25.14 | The only author from the authors table whose last name contains o as the second letter.

38 25.4.3 ORDER BY Clause Optional ORDER BY clause
SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT authorID, firstName, lastName FROM authors ORDER BY lastName ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC ORDER BY lastName DESC

39 Fig. 25.15 | Sample data from table authors in ascending order by lastName.

40 Fig. 25.16 | Sample data from table authors in descending order by lastName.

41 25.4.3 ORDER BY Clause (Cont.) ORDER BY multiple fields
ORDER BY column1 sortingOrder, column2 sortingOrder, … SELECT authorID, firstName, lastName FROM authors ORDER BY lastName, firstName

42 Fig. 25.17 | Sample data from authors in ascending order by lastName and firstName.

43 25.4.3 ORDER BY Clause (Cont.) Combine the WHERE and ORDER BY clauses
SELECT isbn, title, editionNumber, copyright, price FROM titles WHERE title LIKE ‘%How to Program’ ORDER BY title ASC

44 Fig | Sampling of books from table titles whose titles end with How to Program in ascending order by title.

45 25.4.4 Merging Data from Multiple Tables: INNER JOIN
Split related data into separate tables Join the tables Merge data from multiple tables into a single view INNER JOIN SELECT columnName1, columnName2, … FROM table1 INNER JOIN table2 ON table1.columnName = table2.column2Name SELECT firstName, lastName, isbn FROM authors, authorISBN INNER JOIN authorISBN ON authors.authorID = authorISBN.authorID ORDER BY lastName, firstName

46 Fig | Sampling of authors and ISBNs for the books they have written in ascending order by lastName and firstName.

47 Software Engineering Observation 25.3
If a SQL statement includes columns with the same name from multiple tables, the statement must precede those column names with their table names and a dot (e.g., authors.authorID).

48 Common Programming Error 25.5
Failure to qualify names for columns that have the same name in two or more tables is an error.

49 25.4.5 INSERT Statement Insert a row into a table
INSERT INTO tableName ( columnName1, … , columnNameN ) VALUES ( value1, … , valueN ) INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ )

50 Fig. 25.20 | Sample data from table Authors after an INSERT operation.

51 Common Programming Error 25.6
It is normally an error to specify a value for an autoincrement column.

52 Common Programming Error 25.7
SQL uses the single-quote (') character as a delimiter for strings. To specify a string containing a single quote (e.g., O’Malley) in a SQL statement, the string must have two single quotes in the position where the single-quote character appears in the string (e.g., 'O''Malley'). The first of the two single-quote characters acts as an escape character for the second. Not escaping single-quote characters in a string that is part of a SQL statement is a SQL syntax error.

53 25.4.6 UPDATE Statement Modify data in a table UPDATE tableName
SET columnName1 = value1, … , columnNameN = valueN WHERE criteria UPDATE authors SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’

54 Fig. 25.21 | Sample data from table authors after an UPDATE operation.

55 25.4.7 DELETE Statement Remove data from a table
DELETE FROM tableName WHERE criteria DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’

56 Fig. 25.22 | Sample data from table authors after a DELETE operation.

57 25.5 Instructions to Install MySQL and MySQL Connector/J
Platform-specific installation requirements: dev.mysql.com/doc/refman/5.0/en/general- installation-issues.html Download your platform’s installer from: dev.mysql.com/downloads/mysql/5.0.html Need only the Windows Essentials package on Microsoft Windows Follow installation instructions for your platform: dev.mysql.com/doc/refman/5.0/en/installing. html

58 25.5 Instructions to Install MySQL and MySQL Connector/J
MySQL Server Instance Configuration Wizard Click Next > then select Standard Configuration and click Next > again. Not necessary to install MySQL as a Windows service for our examples Uncheck Install as a Windows Service Check Include Bin Directory in Windows PATH Click Next > then click Execute to perform the server configuration. Click Finish to close the wizard.

59 25.5 Instructions to Install MySQL and MySQL Connector/J
Install MySQL Connector/J Must install Connector/J JDBC driver from: dev.mysql.com/downloads/connector/j/ html Download mysql-connector-java zip Extract mysql-connector-java zip to your hard disk into the folder mysql-connector-java-5.0.4 Documentation for MySQL Connector/J is in connector-j.pdf in the docs subdirectory of mysql-connector-java-5.0.4 Docs also online at dev.mysql.com/doc/connector/j/en/ connector-j.html

60 25.6 Instructions on Setting MySQL User Account
Set up a user account Start database server mysqld-nt.exe on Windows Start the MySQL monitor mysql –h localhost –u root Select the built-in database mysql USE mysql; Add the user account jhtp7 and specify privileges create user identified by 'jhtp7'; grant select, insert, update, delete, create, drop, references, execute on *.* to Exit the MySQL Monitor exit;

61 25.7 Creating Database books in MySQL
Create books database Open Command Prompt and change to the directory containing the SQL script books.sql Start the MySQL monitor mysql –h localhost –u jhtp7 –p Execute the script source books.sql; Exit the MySQL Monitor exit;

62 25.8 Manipulating Databases with JDBC
Connect to a database Query the database Display the results of the query

63 25.8.1 Connecting to and Querying a Database
DisplayAuthors Retrieves the entire authors table Displays the data in the standard output stream Example illustrates Connect to the database Query the database Process the result

64 25.8.1 Connecting to and Querying a Database
JDBC Java Database Connectivity JDBC driver Enable Java applications to connect to database Enable programmers to manipulate databases using JDBC Execute SQL statements Retrieve results Present data in a user frendly interface Propagete changes back to database JDBC API Classes and interfaces -

65 25.8.1 Connecting to and Querying a Database
JDBC API Establishing connections with databases Sending SQL statements to databases Processing the results of the SQL statements Obtaining database metadata Four key interfaces: Driver, Connection, Statement, ResultSet JDBC API define these interfaces JDBC driver vendors provide implementations for them Programmers use the interfaces

66 25.8.1 Connecting to and Querying a Database
Following steps Loading drivers Establishing connections Creating statements Executing statements Obtain metadata Processing resultSet

67 Loading Drivers Appropriate driver must be loaded For Access databases
Class.forName(String DriverClassName); Drivers are concrete classes that imlement Java.sql.Driver – interface For Access databases Driver: sun.jdbc.odbc.JdbcOdbcDriver in JDK After Jav a 6 automatically found and loaded

68 Establishing connections
To connected to the database use static method getConnection(String databseuRL) Of the DriverManager class Where databaseURL is the unique identiier of the database on the internet

69 Establishing connections
For Access databases databaseURL: Jdbc:odbc:datasource An ODBC datasource canbe created using ODBC Administrator of Windows Exaaple: Connection connection = DriverManager.getConnections(databaseURL,userName,passpard); Connection connection = DriverManager.getConnections(“jdbc:odbc:Personel”,””,””);

70 Creating statements Once a connection object is created
in previous slide : connection Statement statement = connection.createStatement(); createStatement method of Connection class is invoked on the connection object Returns a Statement object on which queries can be executed

71 Creating statements Executing queries: Examples:
Use executeQuery, execıte or executeUpdate Methods of the Statement class on the statement object ExecuteQuery returns a resultSet object Methods of Statemet on a statement object Examples: statement.executeQuery(“SELECT name from autors”); On the statement object executeOuery method is inovked sending the SQL query as a String

72 Processing resultSet The resultSet maintains a table whose current raw can be retrieved ExecuteQuery method returns a ResultSet object

73 Example The first example queries a simple databes
An Access database ODBC source name Personel The database has an employee tabhle The employee table cansists of EmployeeID and Name columns

74 Example (cont.) // Import for the JDBC classes and interfaces from package java.sql import java.sql.*; public class DataBase { static final String DATASOURCE = “jdbc:odbc:Personel"; public static void main(String[] args) throws Exception { Connection connection; // Connection object Statement statement; // connection statement connection = DriverManager.getConnection(DATASOURCE,"",""); statement=connection.createStatement();

75 Example (cont.) // insert a new employee
String newInsert = "INSERT INTO employee (employeeID,name) VALUES (6,‘Ali')"; statement.execute(newInsert); // query database String query = "SELECT * FROM employee"; ResultSet results = statement..executeQuery(query);

76 Example (cont.) // Position the ResultSet cursor to the first row in the ResultSet with method next while(results.next()) { // Extract the contents of one column in the current row System.out.print(results.getString(“EmloyeeID")); // System.out.print(results.getString(1)); System.out.print("\t"); System.out.print(results.getString(“Name")); // System.out.print(results.getString(2)); System.out.println(); } // end while loop

77 Example (cont.) // Close the Statement and the database Connection.
results.close(); statement.close(); connection.close(); } // end main } // end Database

78 Example – different version
// Imports for the JDBC classes and interfaces from package java.sql import java.sql.Connection; import java.sql.Statement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class Database2 { static final String DATASOURCE = “jdc:odbc:Personel";

79 Example – different version (cont.)
public static void main(String[] args) throws SQLException, ClassNotFoundException { Connection connection; // Connection referance Statement statement; // connection statement connection = DriverManager.getConnection(, DATASOURCE,""); statement = connection.createStatement(); String query = "SELECT * FROM employee"; ResultSet results = statement.executeQuery(query); ResultSetMetaData metaData = results.getMetaData();

80 Example – different version (cont.)
int numberOfColunms = metaData.getColumnCount(); System.out.println(“Nuber of colluncs:"+numberOfCollunms); for(int i=1;i<=muberOfCollunms;i++) System.out.printf("%-12s\t", metaData.getColumnName(i)); System.out.println();

81 Example – different version (cont.)
// Position the ResultSet cursor to the first row in the ResultSet with method next while(results.next()) { // Extract the contents of one column in the current row for(int i = 1;i<=nuberOfCollumns;i++) System.out.printf("%- 12s\t",results.getObject(i)); System.out.println(); } // Close the Statement and the database Connection. results.close(); statement.close(); connection.close(); } // end main } // end Database

82 Example – with exception handling
// Import for the JDBC classes and interfaces from package java.sql import java.sql.*; public class Database3 { static final String DATASOURCE = “jdc:odbc:Personel"; public static void main(String[] args) throws SQLException, ClassNotFoundException { Connection connection; // Connection referance Statement statement; // connection statement

83 Example – with exception handling
// connect to database Personel and query database try { // establish connection to database connection = DriverManager.getConnection(DATASOURCE, "", "" ); // create Statement for querying database statement = connection.createStatement(); // query database resultSet = statement.executeQuery(query);

84 Example – with exception handling
// process query results // Obtains the metadata for the ResultSet. ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); System.out.println( "Authors Table of Books Database:\n" ); for ( int i = 1; i <= numberOfColumns; i++ ) System.out.printf( "%-8s\t", metaData.getColumnName( i ) ); System.out.println();

85 Example – with exception handling
// Position the ResultSet cursor to the first row in the ResultSet with method next while ( resultSet.next() ) { // Extract the contents of one column in the current row for ( int i = 1; i <= numberOfColumns; i++ ) System.out.printf( "%-8s\t", resultSet.getObject( i ) ); System.out.println(); } // end while } // end try // Catch SQLException, which is thrown if the query execution or ResultSet process fails catch ( SQLException sqle ) { sqle.printStackTrace(); } // end catch // ClassNotFoundException is thrown if the class loader cannot locate the driver class catch ( ClassNotFoundException cnf ) { cnf.printStackTrace();

86 Example – with exception handling
Finally { // ensure resultSet, statement and connection are closed // Close the Statement and the database Connection. try { resultSet.close(); statement.close(); connection.close(); } // end try catch ( Exception e ) { e.printStackTrace(); } // end catch } // end finally } // end main } // end class Database3

87 Example – with exception handling
// Initialize a Connection reference called connection. // Invokes Connection method createStatement to obtain an object that implements interface Statement. // Use the Statement object’s executeQuery method to execute a query that selects all the author information from table authors. // Obtains the metadata for the ResultSet. // Uses ResultSetMetaData method getColumnCount to retrieve the number of columns in the ResultSet. // Obtain column name using method getColumnName // Position the ResultSet cursor to the first row in the ResultSet with method next // Extract the contents of one column in the current row

88 25.8.1 Connecting to and Querying a Database
import java.sql.*; public class dbConnection { static final String DATASOURCE = “jdc:odbc:Personel"; public static void main(String[] args) throws Exception { Connection con = DriverManager.getConnection(DATASOURCE,"",""); Statement st = con.createStatement();

89 25.8.1 Connecting to and Querying a Database
PreparedStatement prSt = con.prepareStatement("insert into empluyee (EmployeeID,Name) values (?,?)"); prSt.setString(1, “7"); prSt.setString(2, “Mehmet"); prSt.executeUpdate(); st.close(); con.close() } // end main } // end dbConnection class

90 Example: An update Query
An example getting information from the user and by connecting to a database update the database Get a new employee: Employee ID and Name from the user from a GUI Insert the new employee to the Employee database

91 Example: An update Query
import javax.swing.*; import java.sql.*; import java.awt.event.*; import java.awt.*; public class DbConnection { public static void main(String[] args)throws Exception { Frame frame = new Frame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); frame.setVisible(true); } // end main } // end class DbConnection

92 Example: An update Query
Frame class extends from JFrame Two labels and two textFields and a button When the user enters new emloyee ID and name Presses the Send button An action event is generated The actionPerformed method gets the values of the two textFields Creates a specific connection object that accept these two strings as arguments Call the connectTo method of over the object to connect to the database

93 Example: An update Query
class Frame extends JFrame{ private JLabel label1; private JLabel label2; private JTextField textField1; private JTextField textField2; private JButton button1; public Frame() { label1=new JLabel("New Employee ID"); label2=new JLabel("New Name"); button1 = new JButton("Send"); textField1 = new JTextField(); textField2 = new JTextField();

94 Example: An update Query
setLayout(new GridLayout(3,2)); add(label1); add(textField1); add(label2); add(textField2); add(button1); ButonHandler handler = new ButonHandler(); button1.addActionListener(handler); } // end of constructor

95 Example: An update Query
private class ButonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String s1 = textField1.getText(); String s2 = textField2.getText(); MyConnection myCon = new MyConnection(s1,s2); myCon.connectTo(); } // end method actionPerformed } // end class ButtonHandler } // end class Frame

96 Example: An update Query
class MyConnection { private String str1; private String str2; public MyConnection(String s1, String s2) { str1 = s1; str2 = s2; } // end constructor

97 Example: An update Query
public void connectTo() { // make the odbc within java String connectionStr = "jdbc:odbc:Personel"; try { Connection con = DriverManager.getConnection( connectionStr,"",""); PreparedStatement prSt = con.prepareStatement("insert into employee values (?,?)");

98 Example: An update Query
prSt.setString(1, str1); prSt.setString(2, str2); prSt.executeUpdate(); } // end try catch (Eexception e) { e.getStackTrace(); } // end catch Finally { prSt.close(); con.close(); } // end finally } // end method connectTo } // end class MyConnection

99 Another Desing Option Frame class MyConnect class Connection class
Get data from the user – to insert a new employee Send the information to an object of MyConnection MyConnect class Having the values of two Strings Prepare a SQL query statement Call a generic Connection class Connection class A generic Connectin class written for geeral purpases Accept Driver Name, dataSource,query Returns a ResultSet reference

100 Another Desing Option Frame and MyConnection classes are the same
But MyConnection’s connectTo method: creates an object from a generic connection class sending drivename,url,username,pasward.and query returns a resultset or for update or insert queries sending and parameters

101 Another Desing Option class MyConnection { private String str1;
private String Driver = …; private String url =…; private ResultSet myResults; private String query = "insert into employee( employeeID, Name) values (“+str1+”,”+str2+”)"

102 Another Desing Option public MyConnection(String s1, String s2) {
str1 = s1; str2 = s2; prepareQuery(); sendQuery(); } // end constructor public void prepareQuery() { // prepare query here } public void sendQuery() { ConnectClass conClass = new ConnectClass(Driver,url,query); myResults = conClass.execute(); } // process results here // other methods } // end class

103 Another Desing Option class ConnectClass { private String driver;
private String url; private String query; private String userName; private String passward; public ConnectClass(String sdrv, String surl, Srring squery) { driver = sdrv; url = surl; query = squery; }

104 Another Desing Option // a generic method for exeuting a general query and // returning its results as a Resultset reference public ResultSet execute() throws Exception { Class.forName(driver); Connection con = DriverManager.getConnection(url,userName,passward); Statement statement = con.createStatement(); return statement..executeQuery(query); } // end method // other methods for get set … } end class

105 Outline Imports for the JDBC classes and interfaces from package java.sql DisplayAuthors .java (1 of 3 ) Declare a String constant that specifies the JDBC driver’s class name Declare a String constant that specifies the database URL Loads the class definition for the database driver.

106 Outline Initialize a Connection reference called connection.
Invokes Connection method createStatement to obtain an object that implements interface Statement. DisplayAuthors .java (2 of 3 ) Use the Statement object’s executeQuery method to execute a query that selects all the author information from table authors. Obtains the metadata for the ResultSet. Uses ResultSetMetaData method getColumnCount to retrieve the number of columns in the ResultSet. Obtain column name using method getColumnName Position the ResultSet cursor to the first row in the ResultSet with method next Extract the contents of one column in the current row

107 Catch SQLException, which is thrown if the query execution or ResultSet process fails
Outline ClassNotFoundException is thrown if the class loader cannot locate the driver class DisplayAuthors .java (3 of 3 ) Close the Statement and the database Connection.

108 Software Engineering Observation 25.4
Most major database vendors provide their own JDBC database drivers, and many third-party vendors provide JDBC drivers as well. For more information on JDBC drivers, visit the Sun Microsystems JDBC Web site, servlet.java.sun.com/products/ jdbc/drivers.

109 Software Engineering Observation 25.5
Most database management systems require the user to log in before accessing the database contents. DriverManager method getConnection is overloaded with versions that enable the program to supply the user name and password to gain access.

110 Fig. 25.24 | Popular JDBC database URL formats.

111 Software Engineering Observation 25.6
Metadata enables programs to process ResultSet contents dynamically when detailed information about the ResultSet is not known in advance.

112 Common Programming Error 25.8
Initially, a ResultSet cursor is positioned before the first row. Attempting to access a ResultSet’s contents before positioning the ResultSet cursor to the first row with method next causes a SQLException.

113 Performance Tip 25.1 If a query specifies the exact columns to select from the database, the ResultSet contains the columns in the specified order. In this case, using the column number to obtain the column’s value is more efficient than using the column name. The column number provides direct access to the specified column. Using the column name requires a search of the column names to locate the appropriate column.

114 Common Programming Error 25.9
Specifying column number 0 when obtaining values from a ResultSet causes a SQLException.

115 Common Programming Error 25.10
Attempting to manipulate a ResultSet after closing the Statement that created the ResultSet causes a SQLException. The program discards the ResultSet when the corresponding Statement is closed.

116 Software Engineering Observation 25.7
Each Statement object can open only one ResultSet object at a time. When a Statement returns a new ResultSet, the Statement closes the prior ResultSet. To use multiple ResultSets in parallel, separate Statement objects must return the ResultSets.

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

118 Outline ResultSetTable Model.java (1 of 7 ) Class ResultSetTableModel extends class AbstractTableModel, which implements interface TableModel. Instance variable keeps track of database connection status

119 Outline Constructor accepts five String arguments—the driver class name, the database URL, the username, the password and the default query to perform Establishes a connection to the database. ResultSetTable Model.java (2 of 7 ) Invokes Connection method createStatement to create a Statement object. Indicate that connect to database is successful Invokes ResultSetTableModel method setQuery to perform the default query.

120 Outline Verify database connection status
Override method getColumnClass to obtain a Class object that represents the superclass of all objects in a particular column Verify database connection status ResultSetTable Model.java (3 of 7 ) 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. Override method getColumnCount to obtain the number of columns in the model’s underlying ResultSet

121 Outline Obtains the number of columns in the ResultSet. (4 of 7 )
ResultSetTable Model.java (4 of 7 ) Override method getColumnName to obtain the name of the column in the model’s underlying ResultSet Obtains the column name from the ResultSet.

122 Outline Override method getColumnCount to obtain the number of rows in the model’s underlying ResultSet ResultSetTable Model.java (5 of 7 ) Override method getValueAt to obtain the Object in a particular row and column of the model’s underlying ResultSet 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.

123 Outline (6 of 7 ) Executes the query to obtain a new ResultSet.
ResultSetTable Model.java (6 of 7 ) 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 fireTableAStructureChanged to notify any JTable using this ResultSetTableModel object as its model that the structure of the model has changed.

124 Outline Verify whether the connection is already terminated
Method disconnectFromDatabase implement an appropriate termination method for class ResultSetTableModel Verify whether the connection is already terminated ResultSetTable Model.java (7 of 7 ) Close the Statement and Connection if a ResultSetTableModel object is garbage collected. Set connectedToDatabase to false to ensure that clients do not use an instance of ResultSetTableModel after that instance has already been terminated

125 Fig. 25.26 | ResultSet constants for specifying ResultSet type.

126 Portability Tip 25.3 Some JDBC drivers do not support scrollable ResultSets. In such cases, the driver typically returns a ResultSet in which the cursor can move only forward. For more information, see your database driver documentation.

127 Portability Tip 25.4 Some JDBC drivers do not support updatable ResultSets. In such cases, the driver typically returns a read-only ResultSet. For more information, see your database driver documentation.

128 Common Programming Error 25.11
Attempting to update a ResultSet when the database driver does not support updatable ResultSets causes SQLFeatureNotSupportedExceptions.

129 Common Programming Error 25.12
Attempting to move the cursor backward through a ResultSet when the database driver does not support backward scrolling causes a SQLException.

130 Fig. 25.27 | ResultSet constants for specifying result properties.

131 Outline DisplayQuery Results.java (1 of 8 ) Declare the database driver class name, database URL, username and password for accessing the database

132 Outline Declare the default query
Declare tableModel to be a reference to ResultSetTableModel DisplayQuery Results.java (2 of 8 ) Create TableModel for results of default query “SELECT * FROM authors”

133 Outline (3 of 8 ) Create JTable delegate for tableModel
DisplayQuery Results.java (3 of 8 ) Create JTable delegate for tableModel

134 Register an event handler for the submitButton that the user clicks to submit a query to the database Outline DisplayQuery Results.java (4 of 8 ) Invoke ResultSetTableModel method setQuery to execute the new query

135 Outline Ensure that the database connection is closed (5 of 8 )
DisplayQuery Results.java (5 of 8 ) Set up TableRowSorter No filter initially

136 Outline Set filter using regular expression (6 of 8 )
DisplayQuery Results.java (6 of 8 )

137 Outline Ensure that the database connection is closed (7 of 8 )
DisplayQuery Results.java (7 of 8 ) Ensure that the database connection is closed when window is closed

138 Outline DisplayQuery Results.java (8 of 8 )

139 25.10 RowSet Interface Interface RowSet Two types of RowSet
Configures the database connection automatically Prepares query statements automatically Provides set methods to specify the properties needed to establish a connection Part of the javax.sql package Two types of RowSet Connected RowSet Connects to database once and remain connected Disconnected RowSet Connects to database, executes a query and then closes connection

140 25.10 RowSet Interface (Cont.)
Package javax.sql.rowset JdbcRowSet Connected RowSet Wrapper around a ResultSet Scrollable and updatable by default CachedRowSet Disconnected RowSet Cache the data of ResultSet in memory Serializable Can be passed between Java application Limitation Amount of data that can be stored in memory is limited

141 Portability Tip 25.5 A RowSet can provide scrolling capability for drivers that do not support scrollable ResultSets.

142 Outline JdbcRowSetTest .java (1 of 3 )

143 Use Sun’s reference implementation of JdbcRowSet interface (JdbcRowSetImpl) to create a JdbcRowSet object Outline Invoke JdbcRowSet method setUrl to specify the database URL Invoke JdbcRowSet method setUsername to specify the username Invoke JdbcRowSet method setUsername to specify the password Invoke JdbcRowSet method setCommand to specify the query Invoke JdbcRowSet method execute to execute the query JdbcRowSetTest .java (2 of 3 )

144 Outline JdbcRowSetTest .java (3 of 3 )

145 25.11 Java DB/Apache Derby As of JDK 6, Sun Microsystems now bundles the open-source, pure Java database Java DB (the Sun branded version of Apache Derby) with the JDK We use the embedded version of Java DB There is also a network version that executes similarly to the MySQL DBMS introduced earlier in the chapter

146 25.11 Java DB/Apache Derby Java DB comes with several batch files to configure and run it First set the environment variable JAVA_HOME to refer to the JDK’s C:\Program Files\Java\jdk1.6.0 installation directory Open the batch file setEmbeddedCP.bat (located in C:\Program Files\Java\jdk1.6.0\db\frameworks\embedded\bin) in a text editor such as Notepad Locate the line rem set DERBY_INSTALL= and change it to set DERBY_INSTALL=C:\Program Files\Java\jdk1.6.0\db Also, comment out the line @FOR %%X in ("%DERBY_HOME%") DO SET DERBY_HOME=%%~sX by preceding it with REM Save your changes and close this file

147 25.11 Java DB/Apache Derby Change directories to C:\Program Files\Java\ jdk1.6.0\db\frameworks\embedded\bin\. Then, type setEmbeddedCP.bat and press Enter to set the environment variables required by Java DB. Embedded Java DB database must reside in the same location as the application that manipulates the database Change to the directory that contains the code for Figs –25.32 Execute the command "C:\Program Files\Java\jdk1.6.0\db\frameworks\embedded\bin\ij" to start the command-line tool for interacting with Java DB. The double quotes are necessary because the path contains a space.

148 25.11 Java DB/Apache Derby At the ij> prompt type
connect 'jdbc:derby:AddressBook;create=true; user=jhtp7;password=jhtp7'; to create the AddressBook database in the current directory. This command also creates the user jhtp7 with the password jhtp7 for accessing the database. To create the database table and insert sample data in the database type run 'address.sql'; To terminate the Java DB command-line tool, type exit;

149 25.12 PreparedStatements PreparedStatements execute more efficiently than Statement objects PreparedStatements can specify parameters

150 25.12 PreparedStatements PreparedStatement to locate all book titles for an author with a specific last name and first name, and to execute that query for several authors: PreparedStatement authorBooks = connection.prepareStatement( "SELECT lastName, firstName, title " "FROM authors INNER JOIN authorISBN " "ON authors.authorID=authorISBN.authorID " "INNER JOIN titles " "ON authorISBN.isbn=titles.isbn " "WHERE lastName = ? AND firstName = ?" ); Question marks (?) are placeholders for values that will be passed as part of the query to the database

151 25.12 PreparedStatements Program must specify the parameter values by using the PreparedStatement interface’s set methods. For the preceding query, both parameters are strings that can be set with PreparedStatement method setString as follows: authorBooks.setString( 1, "Deitel" ); authorBooks.setString( 2, "Paul" ); setString automatically escapes String parameter values as necessary (e.g., the quote in the name O’Brien) More info at java.sun.com/javase/6/docs/api/ java/sql/PreparedStatement.html

152 Performance Tip 25.2 PreparedStatements are more efficient than Statements when executing SQL statements multiple times and with different parameter values.

153 Error-Prevention Tip 25.1 Use PreparedStatements with parameters for queries that receive String values as arguments to ensure that the Strings are quoted properly in the SQL statement.

154 Outline Person.java (1 of 3 )

155 Outline Person.java (2 of 3 )

156 Outline Person.java (3 of 3 )

157 Outline All program to use PreparedStatements (1 of 7 )
PersonQueries .java (1 of 7 ) Declare PreparedStatements Note that we do not load the Java DB driver first. JDBC 4’s automatic driver discovery is used here.

158 Outline Configure each PreparedStatement. Each ? represents a parameter. PersonQueries .java (2 of 7 )

159 Outline Executes the query in PreparedStatement selectAllPeople.
PersonQueries .java (3 of 7 ) Process the ResultSet.

160 Outline PersonQueries .java (4 of 7 ) Specify the parameter to PreparedStatement selectPeopleByLastName. Executes the query in PreparedStatement selectPeopleByLastName.

161 Process the ResultSet. Outline PersonQueries .java (5 of 7 )

162 Outline PersonQueries .java (6 of 7 ) Specify the parameters to PreparedStatement insertNewPerson. Executes the insert operation in PreparedStatement insertNewPerson.

163 Outline PersonQueries .java (7 of 7 )

164 Outline AddressBook Display.java (1 of 14 )

165 Outline AddressBook Display.java (2 of 14 )

166 Outline AddressBook Display.java (3 of 14 )

167 Outline AddressBook Display.java (4 of 14 )

168 Outline AddressBook Display.java (5 of 14 )

169 Outline AddressBook Display.java (6 of 14 )

170 Outline AddressBook Display.java (7 of 14 )

171 Outline AddressBook Display.java (8 of 14 )

172 Outline AddressBook Display.java (9 of 14 )

173 Outline AddressBook Display.java (10 of 14 ) Executes the query in PreparedStatement selectPeopleByLastName from class PersonQueries.

174 Outline AddressBook Display.java (11 of 14 )

175 Outline Executes the query in PreparedStatement selectAllPeople from class PersonQueries. AddressBook Display.java (12 of 14 )

176 Outline Executes the insert operation in PreparedStatement insertNewPerson from class PersonQueries. AddressBook Display.java (13 of 14 )

177 Outline AddressBook Display.java (14 of 14 )

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

179 Portability Tip 25.6 Although the syntax for creating stored procedures differs across database management systems, the interface CallableStatement provides a uniform interface for specifying input and output parameters for stored procedures and for invoking stored procedures.

180 Portability Tip 25.7 According to the Java API documentation for interface CallableStatement, for maximum portability between database systems, programs should process the update counts or ResultSets returned from a CallableStatement before obtaining the values of any output parameters.

181 25.13 Transaction Processing
Many applications require guarantees that a series of database insertions, updates and deletions executes properly before the applications continue processing the next database operation Enables a program that interacts with a database to treat a database operation (or set of operations) as a single operation Known as an atomic operation or a transaction At the end of a transaction, decide to commit or roll back

182 25.13 Transaction Processing
Committing a transaction finalizes the database operation(s); all insertions, updates and deletions performed as part of the transaction cannot be reversed without performing a new database operation Rolling back a transaction leaves the database in its state prior to the database operation

183 25.13 Transaction Processing
Methods of interface Connection setAutoCommit specifies whether each SQL statement commits after it completes (a true argument) or if several SQL statements should be grouped as a transaction (a false argument) If the argument to setAutoCommit is false, the program must follow the last SQL statement in the transaction with a call to Connection method commit or rollback getAutoCommit determines the autocommit state for the Connection.


Download ppt "12 Accessing Databases with JDBC."

Similar presentations


Ads by Google