Beruflich Dokumente
Kultur Dokumente
JDBC Overview
Recipe for a Basic JDBC application
Mapping SQL type to Java types Updating a Table Error and Warnings PreparedStatement Database Metadata Transactions JDBC 2.0 and 3.0
Appendix
Setting up ODBC with MS Access
Copyright Objective Consulting JDBC 1
JDBC - Basics
Database Management Systems (DBMS), usually simply referred as databases, provide data storage and data management for applications with large volumes of data. Example databases (DBMSs) are Oracle, Sybase, IBM UDB, MS SQL Server, MS Access. The common feature of most databases is that they support the Structured Query Language (SQL). SQL provides commands for creating, reading, and updating database tables. JDBC makes possible
The development of Java, therefore portable, programs to access any SQL compliant database. Development of optimized low-level database specific drivers by DB vendors and third-party developers.
JDBC 2
JDBC 3
JDBC 4
JDBC - Basics
JDBC is a Java language API that provides access to databases which utilize the Structured Query Language (SQL). JDBC drivers which implement the JDBC API must support at least SQL-92. The result is that SQL DB applications can be entirely written in Java. The majority of the code of these applications can be database neutral by utilizing the SQL that is not vendor specific.
JDBC 5
JDBC - Basics
Java application
JDBC API
Bridge
ODBC driver
Database
Sybase Database
Oracle Database
JDBC 6
JDBC - Basics
JDBC drivers are categorized into 4 types.
Type 1: JDBC-ODBC Bridge Drivers Type 2: Native-API (partly Java) Drivers Type 3: Net-Protocol All-Java Middleware Drivers Type 4: Native-protocol All-Java Drivers
Type 1 JDBC-ODBC bridge drivers are useful for testing and very small desktop systems only. Most database venders supply a type 3 or type 4 driver.
Copyright Objective Consulting JDBC 7
JDBC - Basics
Most DB vendors supply a JDBC driver with their DBMS. You can also purchase a 3rd party driver. Driver selection is based on the architecture of the application (1-tier vs 3-tier) and tradeoffs of speed, portability, reliability. The examples in this presentation use the JDBCODBC driver that comes with the JDK.
For a comprehensive list of JDBC drivers see Suns web site http://java.sun.com/products/jdbc/jdbc.drivers.html
JDBC 8
JDBC - Basics
Client
Client (Visual presentation)
HTTP, RMI,etc..
Middle tier (business logic)
JDBC
JDBC
Database protocol Database protocol Database Database
JDBC 10
The portion after jdbc: is database specific. Consult the docs for your specific database.
JDBC 12
The DriverManager will select the appropriate driver and setup the DB connection. If the DB does not require a user and password then use blanks.
static final String user = "; static final String password = ";
Copyright Objective Consulting JDBC 13
A common technique is to create the connection during program initialization and use it throughout the life of the application. Tear down the connection upon program exit.
JDBC 14
Statement
Basic SQL statements
PreparedStatement
Precompiled SQL for improved performance
CallableStatement
To execute stored procedures in the database
For now we will look at the Statement class use to execute basic SQL statements.
Copyright Objective Consulting JDBC 15
In the next examples we will use a Statement object to execute SQL queries.
JDBC 16
JDBC 17
// // //
// Step 4 use the Statement object to execute SQL stmt.executeQuery(anSQLquery); stmt.executeUpdate(anSQLupdate); stmt.execute(anSQLstatement); // a query or update
JDBC 18
JDBC 19
ResultSet rs = stmt.executeQuery(query);
// Step 5 process the results row by row while( rs.next() ) { System.out.println(rs.getString(FirstName)); }
A result set can be viewed as a table of data containing rows as a result of a query. The cursor is initially positioned before the first row. The columns returns are those specified in the query.
Copyright Objective Consulting JDBC 20
10
JDBC 22
11
JDBC 23
3. Create a statement
Statement stmt = dbConnection.createStatement();
12
Mapping SQL type to Java types Updating a Table Error and Warnings PreparedStatement Database Metadata Transactions JDBC 2.0 and 3.0
Appendix
Setting up ODBC with MS Access
Copyright Objective Consulting JDBC 25
JDBC - ResultSet
Executing an SQL query returns a ResultSet The ResultSet can be viewed as a table containing the columns specified in the query. The cursor is initially positioned before first row. In JDBC 1.0 the result set can be traversed only in the forward direction via the next() method.
The result set can be traversed only once
In JDBC 2.0 ResultSets can be traversed in both directions We will focus on JDBC 1.0 features since they are common to all applications and your DB may not have a JDBC 2.0 compliant driver or you may have to maintain older code.
Copyright Objective Consulting JDBC 26
13
ResultSet rs = stmt.executeQuery(query);
// Step 5 process the results row by row while(rs.next()) { System.out.println(rs.getString(FirstName)); }
A result set is a table of data containing rows as a result of a query. The cursor is initially positioned before the first row. The columns returns are those specified in the query.
Copyright Objective Consulting JDBC 27
14
Getting the data using the column number is more efficient. However if the SQL query column order changes the index will have to be changed; this is not required if retrieving using column names. Columns should be processed from left to right otherwise you may encounter errors.
Copyright Objective Consulting JDBC 29
15
JDBC 31
Java Type
String String String java.math.BigDecimal java.math.BigDecimal Boolean (boolean) Integer (byte) Integer (short) Integer (int) Long (long) Float (float)
Copyright Objective Consulting
getXXX() method
getString() getString() getString() getBigDecimal() getBigDecimal() getBoolean() getByte() getShort() getInt() getLong() getFloat()
JDBC 32
16
Java Type
Double Double byte[] byte[] byte[] java.sql.Date java.sql.Time java.sql.Timestamp (double) (double)
getXXX() method
getDouble() getDouble() getBytes() getBytes() getBytes() getDate() getTime() getTimestamp()
JDBC 33
These methods are useful to writing generic display methods and for preventing errors. The result set metadata also has a method to determine how many columns were returned. Next we will see a simple example.
Copyright Objective Consulting JDBC 34
17
JDBC 35
JDBC 36
18
In the next examples we will use a Statement object to execute SQL updates.
JDBC 37
JDBC 38
19
JDBC - statement.executeUpdate()
A Java program to find the row with the matching first name and update the e-mail address column in the table.
JDBC 39
JDBC - statement.executeUpdate()
Query shows that the table was updated
JDBC 40
20
JDBC - statement.executeUpdate()
public void actionPerformed(ActionEvent evt) { String name = theName.getText(); String email = theEmail.getText(); String SQLupdate = "Update Students Set emailname = '" + email + "' " + "Where FirstName = '" + name + "'"; // single quotes Statement stmt = theConnection.createStatement(); int n = stmt.executeUpdate(SQLupdate); if (n == 0) { System.out.println(No rows updated); }
JDBC 41
JDBC - statement.executeUpdate()
public void actionPerformed(ActionEvent evt) { String name = theName.getText(); String email = theEmail.getText(); String SQLupdate = "Update Students Set emailname = '" + email + "' "+ "Where FirstName = '" + name + "'"; Statement stmt = theConnection.createStatement(); int n = stmt.executeUpdate(SQLupdate); if (n == 0) { System.out.println(No rows updated); }
JDBC 42
21
JDBC 43
Useful methods
String String int SQLException getMessage(); getSQLState(); getErrorCode(); getNextException();
Copyright Objective Consulting JDBC 44
22
JDBC 46
23
JDBC - PreparedStatement
Recall that there are three JDBC statement classes. Statement
Basic SQL statements
PreparedStatement
Precompiled SQL for improved performance CallableStatement
To execute stored procedures in the database
Now we will look at the PreparedStatement class which is used to improve performance.
Copyright Objective Consulting JDBC 48
24
JDBC - PreparedStatement
When the database engine executes a SQL query via executeQuery() it must process the SQL statement. Processing includes parsing and optimizing the SQL statement.
Parsing checking syntax, are the objects (table names, etc) in the DB, are the data conversion legal Optimizing finding the best access path
If the SQL statement is used frequently then doing the overhead processing in advance (preparing) can improve performance. (approx. 2 to 10 times faster depending on the the
complexity of the SQL statement, number of iterations, etc.)
JDBC 49
JDBC - PreparedStatement
The Connection object performs the parsing/preparation. The PreparedStatement has place-holders for the parameters that will be used when the statement is executed. The values for the parameters are set using one of the setXXX() methods. Assume we have a table to keep track of student assignments. The value of an assignment is a grade. We want to get the value of all assignments for a given student.
String query1 = select assgn1, assgn2, assgn3 from studentAssignments where firstname = ? and lastname = ?; PreparedStatement ps1 = conn.prepareStatement(query1); ps1.setString(1, John); ps1.setString(2, Doe); ResultSet rs = ps1.executeQuery();
Copyright Objective Consulting JDBC 50
25
JDBC - PreparedStatement
The values of parameters set via the setXXX() methods is preserved after the statement is executed. This is convenient if some of the values do not change before the next execution. However you may want to clear the values.
// Get values from JTextFields on a GUI
String firstName = textFieldFirstName.getText(); String lastName = textFieldLastName.getText();
JDBC - Transactions
There are situations in which we must treat a number of DB operations (queries, updates) as an atomic action.
Must update more than one table. If one update fails then want to back out change changes that have already been posted. Two users/threads may be operating on the same set of data. Similar to synchronizing threads, create an atomic action.
26
JDBC - Transactions
A transactions consists of a group of operations.
The transactions is only permanently posted to the database if it is committed. If the program terminates abnormally the transaction is automatically rolled back. By default each JDBC operations occur in a transaction that is automatically committed.
try { conn.setAutoCommit(false);// default commits each operation stmt.executeQuery(aQuery); stmt.executeUpdate(updateOne); stmt.executeQuery(updateTwo); conn.commit(); // Commit the transaction } catch( SQLException se) { conn.rollback(); // back out changes temporarily posted }
Copyright Objective Consulting JDBC 53
JDBC - Transactions
Databases support various transaction isolation levels. An isolation level defines when db changes become visible to other transactions. JDBC defines 5 isolation levels. The underlying database defines which levels are supported. The default isolation level depends on the driver. Consult your DB and driver documentation.
Example: Minimal transaction isolation allow dirty reads. Other transactions can see the results of SQL operations before the transaction is committed. If the transaction is rolled back other transactions will be left with invalid data.
try { conn = DriverManager.getConnection(DB_URL, USER, PASSWD); conn.setTransactionIsolationLevel( Connection.TRANSACTION_READ_UNCOMMITTED); conn.setAutoCommit(false);// default commits each operation . } catch( SQLException se) { conn.rollback(); // back out changes temporarily posted }
JDBC 54
27
JDBC - Transactions
Note that each transaction requires a connection object. Therefore, multiple transactions require multiple connections. Options are:
Create a connection fore each client request
This can be too time consuming. Ok for transactions that occur infrequently and for which the overhead of creating connection is acceptable. Not scalable
Create a number of connections in advance (do connection pooling) Use JDBC 2.0 connection pooling
Copyright Objective Consulting JDBC 55
JDBC 56
28
We can get detailed information about the database (set of tables) as a whole using the DatabaseMetadata.
JDBC 57
Connection conn = DriverManager.getConnection(DB_URL, ,); DatabaseMetaData dbMD = conn.getMetaData(); System.out.println(Driver: + dbMD.getDriverName()); String[] tableTypes = { TABLE }; ResultSet allTables = dbMd.getTables(null,null,null,tableTypes); while(allTable.next()) { String tableName = allTables.getString(TABLE_NAME); System.out.println(Table Name: + tableName); } Copyright Objective Consulting JDBC 58
29
JDBC 59
JDBC Summary/Review
We have seen the following topics: JDBC Overview
Recipe for a Basic JDBC application
Mapping SQL type to Java types Updating a Table Error and Warnings PreparedStatement Database Metadata Transactions JDBC 2.0 and 3.0 BONUS Appendix to help you setup ODBC to play @ home.
Copyright Objective Consulting JDBC 60
30
The ODBC driver is included with the Windows OS. Alternatively you could try setup MySQL (www.mysql.org)
JDBC 61
JDBC 62
31
JDBC - ODBC
Control Panel Double-click the ODBC data sources applet.
JDBC 63
JDBC - ODBC
Click on User Data Source Name (DSN) or System DSN tab. All existing Data Sources will be displayed.
JDBC 64
32
JDBC - ODBC
I chose User DSN for this example. Choose a driver. See next slide.
JDBC 65
JDBC 66
33
JDBC - ODBC
Choose the Data Source Name This will be used in your code as part of the DB URL.
JDBC 67
JDBC - ODBC
Make the link between the DSN and the database by selecting the database. Press OK
JDBC 68
34
JDBC - ODBC
The Database is now listed. Press OK. Done.
JDBC 69
JDBC - ODBC
The Data Source Name is now in the list of user or system DSNs.
JDBC 70
35
JDBC - ODBC
This example shows how to setup ODBC access. Obtain MS-Access or an Access DB and the Access runtime components. The JDBC-ODBC driver comes with the JDK. The JDBC-ODBC driver supports only JDBC 1.0
there may be a JDBC 2.0 driver in the future
The ODBC driver is included with the Windows OS. Alternatively you could try setup MySQL (www.mysql.org)
Copyright Objective Consulting JDBC 71
36