JDBC and Database Programming in Java
JDBC and Database Programming in Java
Programming in Java
Type II
JDBC CLI (.lib)
“Native”
Type IV
“Pure”
Type I Drivers
Use bridging technology
Requires installation/configuration on client
machines
Not good for Web
e.g. ODBC Bridge
Type II Drivers
Native API drivers
Requires installation/configuration on client
machines
Used to leverage existing CLI libraries
Usually not thread-safe
Mostly obsolete now
e.g. Intersolv Oracle Driver, WebLogic
drivers
Type III Drivers
Calls middleware server, usually on
database host
Very flexible -- allows access to multiple
databases using one driver
Only need to download one driver
But it’s another server application to install
and maintain
e.g. Symantec DBAnywhere
Type IV Drivers
100% Pure Java -- the Holy Grail
Use Java networking libraries to talk
directly to database engines
Only disadvantage: need to download a new
driver for each database engine
e.g. Oracle, mSQL
Part III: JDBC APIs
java.sql
JDBC is implemented via classes in the
java.sql package
Loading a Driver Directly
Driver d = new
foo.bar.MyDriver();
Connection c = d.connect(...);
Not recommended, use DriverManager
instead
Useful if you know you want a particular
driver
DriverManager
DriverManager tries all the drivers
Uses the first one that works
When a driver class is first loaded, it
registers itself with the DriverManager
Therefore, to register a driver, just load it!
Registering a Driver
statically load driver
Class.forName(“foo.bar.MyDriver”);
Connection c =
DriverManager.getConnection(...);
or use the jdbc.drivers system
property
JDBC Object Classes
DriverManager
Loads, chooses drivers
Driver
connects to actual database
Connection
a series of SQL statements to and from the DB
Statement
a single SQL statement
ResultSet
the records returned from a Statement
JDBC Class Usage
DriverManager
Driver
Connection
Statement
ResultSet
JDBC URLs
jdbc:subprotocol:source
each driver has its own subprotocol
each subprotocol has its own syntax for the
source
jdbc:odbc:DataSource
e.g. jdbc:odbc:Northwind
jdbc:msql://host[:port]/database
e.g.
jdbc:msql://foo.nowhere.com:4333/accounting
DriverManager
Connection getConnection
(String url, String user,
String password)
Connects to given JDBC URL with given
user name and password
Throws java.sql.SQLException
returns a Connection object
Connection
A Connection represents a session with a specific
database.
Within the context of a Connection, SQL statements are
executed and results are returned.
Can have multiple connections to a database
NB: Some drivers don’t support serialized connections
Fortunately, most do (now)
Also provides “metadata” -- information about the
database, tables, and fields
Also methods to deal with transactions
Obtaining a Connection
String url = "jdbc:odbc:Northwind";
try {
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }
Connection Methods
Statement createStatement()
returns a new Statement object
PreparedStatement prepareStatement(String
sql)
returns a new PreparedStatement object
CallableStatement prepareCall(String sql)
returns a new CallableStatement object
Why all these different kinds of statements?
Optimization.
Statement
A Statement object is used for executing a
static SQL statement and obtaining the
results produced by it.
Statement Methods
ResultSet executeQuery(String)
Execute a SQL statement that returns a single
ResultSet.
int executeUpdate(String)
Execute a SQL INSERT, UPDATE or DELETE
statement. Returns the number of rows changed.
boolean execute(String)
Execute a SQL statement that may return multiple
results.
Why all these different kinds of queries?
Optimization.
ResultSet
A ResultSet provides access to a table of data
generated by executing a Statement.
Only one ResultSet per Statement can be open at
once.
The table rows are retrieved in sequence.
A ResultSet maintains a cursor pointing to its
current row of data.
The 'next' method moves the cursor to the next
row.
you can’t rewind
ResultSet Methods
boolean next()
activates the next row
the first call to next() activates the first row
returns false if there are no more rows
void close()
disposes of the ResultSet
allows you to re-use the Statement that created
it
automatically called by most Statement
methods
ResultSet Methods
Type getType(int columnIndex)
returns the given field as the given type
fields indexed starting at 1 (not 0)
Type getType(String columnName)
same, but uses name of field
less efficient
int findColumn(String columnName)
looks up column index given column name
ResultSet Methods
String getString(int columnIndex)
boolean getBoolean(int columnIndex)
byte getByte(int columnIndex)
short getShort(int columnIndex)
int getInt(int columnIndex)
long getLong(int columnIndex)
float getFloat(int columnIndex)
double getDouble(int columnIndex)
Date getDate(int columnIndex)
Time getTime(int columnIndex)
Timestamp getTimestamp(int columnIndex)
ResultSet Methods
String getString(String columnName)
boolean getBoolean(String columnName)
byte getByte(String columnName)
short getShort(String columnName)
int getInt(String columnName)
long getLong(String columnName)
float getFloat(String columnName)
double getDouble(String columnName)
Date getDate(String columnName)
Time getTime(String columnName)
Timestamp getTimestamp(String columnName)
isNull
In SQL, NULL means the field is empty
Not the same as 0 or “”
In JDBC, you must explicitly ask if a field
is null by calling ResultSet.isNull(column)
Sample Database
Employee ID Last Name First Name
1 Davolio Nancy
2 Fuller Andrew
3 Leverling Janet
4 Peacock Margaret
5 Buchanan Steven
SELECT Example
Connection con =
DriverManager.getConnection(url,
"alex", "8675309");
Statement st = con.createStatement();
ResultSet results =
st.executeQuery("SELECT EmployeeID,
LastName, FirstName FROM Employees");
SELECT Example (Cont.)
while (results.next()) {
int id = results.getInt(1);
String last = results.getString(2);
String first = results.getString(3);
System.out.println("" + id + ": " +
first + " " + last);
}
st.close();
con.close();
Mapping Java Types to SQL
Types
SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Database Time
Times in SQL are notoriously unstandard
Java defines three classes to help
java.sql.Date
year, month, day
java.sql.Time
hours, minutes, seconds
java.sql.Timestamp
year, month, day, hours, minutes, seconds, nanoseconds
usually use this one
Modifying the Database
use executeUpdate if the SQL contains
“INSERT” or “UPDATE”
Why isn’t it smart enough to parse the SQL?
Optimization.
executeUpdate returns the number of rows
modified
executeUpdate also used for “CREATE
TABLE” etc. (DDL)
INSERT example
Optimized Statements
Prepared Statements
SQL calls you make again and again
allows driver to optimize (compile) queries
created with Connection.prepareStatement()
Stored Procedures
written in DB-specific language
stored inside database
accesed with Connection.prepareCall()
JDBC Class Diagram
Whoa!
Metadata
Connection:
DatabaseMetaData getMetaData()
ResultSet:
ResultSetMetaData getMetaData()
ResultSetMetaData
What's the number of columns in the ResultSet?
What's a column's name?
What's a column's SQL type?
What's the column's normal max width in chars?
What's the suggested column title for use in printouts and displays?
What's a column's number of decimal digits?
Does a column's case matter?
Is the column a cash value?
Will a write on the column definitely succeed?
Can you put a NULL in this column?
Is a column definitely not writable?
Can the column be used in a where clause?
Is the column a signed number?
Is it possible for a write on the column to succeed?
and so on...
DatabaseMetaData
What tables are available?
What's our user name as known to the
database?
Is the database in read-only mode?
If table correlation names are supported, are
they restricted to be different from the
names of the tables?
and so on…