Java Database Connectivity
Java Database Connectivity
5
Developing Database Applications
Using JDBC
##.The JDBC API consists of classes and interfaces
for
establishing connections with databases,
sending SQL statements to databases,
processing the results of the SQL statements, and
obtaining database metadata.
Four key interfaces are needed to develop any
database application using Java:
Driver,
Connection,
Statement, and
ResultSet
The JDBC API defines these interfaces.
The JDBC driver vendors provide implementation
6
for them.
Developing Database …
The relationship of these interfaces is shown
below
7
Developing Database …
A JDBC application loads an appropriate driver
using the Driver interface.
Connection to the database will be taken place
using the connection interface,
Creating and executing SQL statements will be
taken place using the Statement interface.
N.B.And the result will be processed using the
ResultSet interface if the statements return
results.
Note. that some statements, such as SQL data
definition statements and SQL data
modification statements, do not return results.
8
Developing Database …
A typical Java program takes the steps
outlined below to access the database.
Loading Drivers
An appropriate driver must be loaded using the
statement shown below before connecting to a
database.
Class.forName("JDBCDriverClass");
# N.B:-A driver is a concrete class that
implements the java.sql.Driver interface.
The drivers for Access, MySQL, and Oracle are
listed below:
9
Developing Database …
Establishing connections
To connect to a database, use the static
method getConnection(databaseURL) in the
DriverManager class, as follows:
Connection con =
DriverManager.getConnection(databaseURL);Wher
e
# N.B. database URL is the unique
identifier of the database .
10
Developing Database …
For example, the following statement creates a
Connection object for the local MySQL database test:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
The databaseURL for an Oracle database specifies
the hostname, the port# where the database listens for
incoming connection requests, and the oracle DBSID
database name to locate a database.
For example, the following statement creates a
Connection object for the Oracle database on
ef.uog.edu with username fedlu and password 1234:
11
Developing Database …
Connection con =
DriverManager.getConnection
(“jdbc:oracle:thin:@ ef.uog.edu:15
21:oradb”,”fedlu”,”1234”);
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
12
Developing Database …
Creating statements
If a Connection object can be envisioned as
a cable linking your program to a database,
##.an object of Statement or its subclass
can be viewed as a cart that delivers SQL
statements for execution by the database
and brings the result back to the program.
Once a Connection object is created, you
can create statements for executing SQL
statements as follows:
Statement stmnt =
13 connection.createStatement();
Developing Database …
Executing statements
The Structured Query Language (SQL) , Data Definition
Examples:
16
Developing Database …
The getString(1), getString(2), and getString(3)
methods retrieve the column values for name, id,
and dept, respectively.
20
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv)
{ System.out.println("-------- Oracle JDBC Connection
Testing ------");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace(); return; }
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection =
DriverManager.getConnection( "jdbc:oracle:thin:
@localhost:1521:XE", “fedlu", “1234");
} catch (SQLException e)
{ System.out.println("Connection Failed! Check
output console"); e.printStackTrace(); return;
} if (connection != null)
System.out.println("You made it, take control your
database now!");
else
System.out.println("Failed to make connection!");
}
}
Additional Example
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","o
racle");
//step3 create the statement object
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * fro
m emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getStr
ing(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e)
{ System.out.println(e);}
}
}
Obtaining Object Descriptions
If you want to know the MySql database name and version, or
the JDBC driver name and version, as well as other information
like maximum numbers of columns you can get them through
the DatabaseMetaData object as shown in the following
sample program:
import java.sql.*;
public class JMySqlDatabaseInfo {
public static void main(String [] args) {
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
“jdbc:mysql://localhost/student_record",
"root","");
// Database and driver info
DatabaseMetaData meta = con.getMetaData();
System.out.println("Server
25
name: “ +
System.out.println("Server version: "+
meta.getDatabaseProductVersion());
System.out.println("Driver name: " +
meta.getDriverName());
System.out.println("Driver version: " +
meta.getDriverVersion());
System.out.println("JDBC major version: "+
meta.getJDBCMajorVersion());
System.out.println("JDBC minor version: "+
meta.getJDBCMinorVersion());
System.out.println("database URL: " +
meta.getURL());
System.out.println("MaxColumnsInTable: " +
new
Integer(meta.getMaxColumnsInTable()));
System.out.println("MaxTableNameLentgh: " +
new
Integer(meta.getMaxTableNameLength()));
26 con.close();
} catch (Exception e) {
Obtaining Object Descriptions
• The output of the code in slide 30 and 31
is shown below
Server name: MySQL
Server version: 5.5.8-log
Driver name: MySQL-AB JDBC Driver
Driver version: mysql-connector-java-5.1.16 ( Revision:
${bzr.revision-id} )
JDBC major version: 4
JDBC minor version: 0
database URL: jdbc:mysql://localhost/student_record
MaxColumnsInTable: 512
MaxTableNameLentgh: 64
27
About Prepared Statements
Prepared Statements are used for
queries that are executed many times
They are parsed (compiled) by the
DBMS only once
Instead of values, use ‘?’
#N.B.Hence, Prepared Statements can
be though of as statements that contain
placeholders to be substituted later with
actual values
28
Querying with PreparedStatement
String queryStr =
"SELECT * FROM employee " +
"WHERE superssn= ? and salary > ?";
PreparedStatement pstmt =
con.prepareStatement(queryStr);
pstmt.setString(1, "333445555");
pstmt.setInt(2, 26000);
ResultSet rs = pstmt.executeQuery();
29
ResultSet
objects provide access to the tables
ResultSet
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
indices start at 1 and not 0!
Type getType(String columnName)
same, but uses name of field
less efficient
33
Transactions and JDBC
Transaction: more than one statement
that must all succeed (or all fail) together
e.g., updating several tables due to customer
purchase
If one fails, the system must reverse all
previous actions
Also can’t leave DB in inconsistent state
halfway through a transaction
COMMIT = complete transaction
ROLLBACK = cancel all actions
34
Transaction Management
Transactions are not explicitly(separately)
opened and closed
The connection has a state called AutoCommit
mode
if AutoCommit is true, then every statement is
automatically committed
if AutoCommit is false, then every statement is
added to an ongoing transaction
Default: true
35
Scrollable ResultSet
Statement createStatement( int resultSetType, int
resultSetConcurrency)
resultSetType:
ResultSet.TYPE_FORWARD_ONLY
--allows only forward movement of the cursor
-when rset.next() returns false, the data is no longer available and the
result set is closed.
ResultSet.TYPE_SCROLL_INSENSITIVE
-backwards, forwards, random cursor movement.
-changes made in the database are not seen in the result set object in
Java memory.
ResultSetTYPE_SCROLL_SENSITIVE
-backwards, forwards, random cursor movement.
-changes made in the database are seen in the
37
Scrollable ResultSet
(cont’d)
public boolean absolute(int row) throws SQLException
-If the given row number is positive, this method moves the cursor to
the given row number (with the first row numbered 1).
-If the row number is negative, the cursor moves to a relative position
from the last row.
-If the row number is 0, an SQLException will be raised .
38
Scrollable ResultSet
(cont’d)
public void beforeFirst() throws SQLException
public void afterLast() throws SQLException
public boolean isFirst() throws SQLException
public boolean isLast() throws SQLException
public boolean isAfterLast() throws
SQLException
public boolean isBeforeFirst() throws
SQLException
39