CS 580 Client-Server Programming Fall Semester, 2000 JDBC |
||
---|---|---|
© 2000, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 13-Nov-00 |
SQL and Java
Some Jargon
SQL Access Group (SAG) - multivendor "Standards" group
SQL Call Level Interface (CLI)
Microsoft's Open Database Connectivity (ODBC)
JDBC
Java Database Connectivity
Sun states
JDBC 2.1 Core
Standard part of JDK 1.2
JDBC drivers must implement JDBC 2.x before you can use it
MySQL driver for JDBC 2.x is in pre-beta release
Additional Features
JDBC 3.0 In final draft form
JDBC Architecture
JDBC driver provides connections to database via drivers
Sample JDBC Use
import java.sql.*; public class SampleMySQL { public static void main(String[] args) throws Exception { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); String database = "jdbc:mysql://fargo.sdsu.edu:5555/WHITNEYR"; String user = "WHITNEYR"; String password = "Top_Secret:)"; Connection toFargo = DriverManager.getConnection(database, user, password); Statement namesTable = toFargo.createStatement(); ResultSet namesFound = namesTable.executeQuery("SELECT * FROM name"); while (namesFound.next() ) { System.out.print( "first: " + namesFound.getString( 1)); System.out.println( "\tlast: " + namesFound.getString( 2)); } toFargo.close(); } }
Using JDBC
Step 1. Load the driver(s)
Step 2. Connect to the database
Step 3. Issue queries and receive results
Loading a Driver
A well-written JDBC driver is loaded using Class.forName
To load the Oracle driver
import java.sql.*; class JdbcTest { public static void main (String args []) throws ClassNotFoundException { Class.forName ("oracle.jdbc.OracleDriver"); } }
This requires that oracle package be in your path
A properly written driver will register itself with the DriverManager class
JDBC Drivers
Java supports four types of JDBC drivers
- JDBC-ODBC bridge plus ODBC driver
JDBC URL Structure
jdbc:<subprotocol>:<subname>
<subprotocol>
jdbc:odbc:<data-source-name>[;<attribute-name>=<attribute-value>]*
jdbc:odbc:qeor7 jdbc:odbc:wombat jdbc:odbc:wombat;CacheSize=20;ExtensionCase=LOWER jdbc:odbc:qeora;UID=kgh;PWD=fooey
DriverManager.getConnection - Using JDBC URL
Three forms:
getConnection(URL, Properties) getConnection(URL, userName, Password) getConnection(URLWithUsernamePassword)
Form 1
static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; DriverManager.getConnection(ARS_URL, "whitney","secret");Form 2
DriverManager.getConnection( "jdbc:oracle:whitney/secret@PutDatabaseNameHere");Form 3
java.util.Properties info = new java.util.Properties(); info.addProperty ("user", "whitney"); info.addProperty ("password","secret"); DriverManager getConnection (ARS_URL ,info );
java.sql.DriverManager
Driver related methods
deregisterDriver(Driver)
getDriver(String)
getDrivers()
registerDriver(Driver)
Connecting to a database
getConnection(String, Properties)
getConnection(String, String, String)
getConnection(String)
getLoginTimeout()
setLoginTimeout(int)
Logging/tracing/Debugging
getLogStream()
setLogStream(PrintStream)
println(String)
Print a message to the current JDBC log stream
Queries
Connection toFargo = DriverManager.getConnection(database, user, password); Statement namesTable = toFargo.createStatement(); ResultSet namesFound = namesTable.executeQuery("SELECT * FROM name");
executeUpdate
Some Result Set Issues
What happens when we call next() too many time?
What happens before we call next
Example Name Table
first |
last |
roger |
whitney |
pete |
stanley |
rat |
cat |
col |
a |
b |
Two Queries public class SampleMySQL { public static void main(String[] args) throws Exception { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); String database = "jdbc:mysql://fargo.sdsu.edu:5555/foo"; Connection toFargo = DriverManager.getConnection(database, "foo", "bar"); Statement namesTable = toFargo.createStatement(); ResultSet namesFound = namesTable.executeQuery("SELECT * FROM name"); for (int k = 0;k< 3;k++) { System.out.println( "first: " + namesFound.getString( 1)); namesFound.next(); } for (int k = 0;k< 3;k++) { sample.next(); System.out.println( "col: " + sample.getString( 1)); } toFargo.close(); } }Result first: roger first: roger first: pete col: a col: b col: b
Mixing ResultSets
Can't have two active result sets on same statement
Statement namesTable = toFargo.createStatement(); ResultSet namesFound = namesTable.executeQuery("SELECT * FROM name"); ResultSet sample = namesTable.executeQuery("SELECT * FROM sample"); for (int k = 0;k< 3;k++) { namesFound.next(); sample.next(); System.out.println( "first: " + namesFound.getString( 1)); System.out.println( "col: " + sample.getString( 1)); }Result first: roger col: a first: roger col: b first: roger col: b
Use Two Statements
Connection toFargo = DriverManager.getConnection(database, user, password); Statement namesTable = toFargo.createStatement(); Statement exampleTable = toFargo.createStatement(); ResultSet namesFound = namesTable.executeQuery("SELECT * FROM name"); ResultSet sample = exampleTable.executeQuery("SELECT * FROM sample"); for (int k = 0;k< 3;k++) { namesFound.next(); sample.next(); System.out.println( "first: " + namesFound.getString( 1)); System.out.println( "col: " + sample.getString( 1)); }
Result first: roger col: a first: pete col: b first: rat col: b
SQL Data Types and Java
SQL
type
|
Java
type
|
CHAR |
String |
VARCHAR |
String
|
LONGVARCHAR |
String |
NUMERIC |
java.math.BigDecimal |
DECIMAL |
java.math.BigDecimal |
BIT |
boolean |
TINYINT |
byte |
SMALLINT |
short |
INTEGER |
int |
BIGINT |
long |
REAL |
float |
FLOAT |
double |
DOUBLE |
double |
BINARY |
byte[] |
VARBINARY |
byte[] |
LONGVARBINARY |
byte[] |
DATE |
java.sql.Date |
TIME |
java.sql.Time |
TIMESTAMP |
java.sql.Timestamp |
Transactions
A transaction consists of one or more statements that have been executed and completed
A transaction ends when a commit or rollback is sent
Connections are opened in auto commit mode:
Transaction Example
import java.sql.*; import java.io.*; class JdbcTest { static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; public static void main (String args []) throws SQLException, ClassNotFoundException, IOException { Class.forName ("oracle.jdbc.OracleDriver"); Connection ARS; ARS =DriverManager.getConnection(ARS_URL, "whitney", "secret"); ARS.setAutoCommit(false); String floodProblem = DELETE FROM AirlineSchedule WHERE from = 'FAR'; String newflight = INSERT INTO AirlineSchedule VALUES ( 'DE', 'SAN', '8:00', '12:00', '909', 'A'); Statement schedule = ARS.createStatement (); schedule.executeUpdate (floodProblem); schedule.executeUpdate (newflight); ARS.commit(); ARS.close(); } }
PreparedStatement
PreparedStatement objects contain SQL statements that have been sent to the database to be prepared for execution
The SQL statements contains variables (IN parameters) which are given values before statement is executed
Only makes sense to use if database and driver keeps statements open after they have been committed
IN parameters are indicated by a ?
Values are set by position
String flightOut = "SELECT * FROM AirlineSchedule WHERE from = ?";
PreparedStatement Example
import java.sql.*; import java.io.*; class JdbcTest { static String ARS_URL = "jdbc:oracle:@PutDatabaseNameHere"; public static void main (String args []) throws SQLException, ClassNotFoundException, IOException { Class.forName ("oracle.jdbc.OracleDriver"); Connection ARS; ARS =DriverManager.getConnection(ARS_URL, "whitney", "secret"); String flightOut = "SELECT * FROM AirlineSchedule WHERE from = ?"; PreparedStatement schedule; schedule = ARS.preparedStatement (flightOut); schedule.setObject( 1, "SAN" ); ResultSet fromSanDiego = schedule.executeQuery (); schedule. clearParameters(); schedule.setObject( 1, "LAX" ); ResultSet fromLA = schedule.executeQuery (); } }
CallableStatement
Some databases have stored procedures (a procedure of SQL statements)
CallableStatement allows a Java program to invoke a stored procedure in a database
DatabaseMetaData
The class DatabaseMetaData allows you to obtain information about the database
The 113 methods in DatabaseMetaData gives you more information than you thought possible
Copyright ©, All rights reserved.
2000 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
OpenContent license defines the copyright on this document.
Previous    visitors since 13-Nov-00    Next