8/7/2019 JDBC lecture
1/28
1
JDBC Java DatabaseJDBC Java DatabaseConnectivityConnectivity
Talking to Databases
Zulqarnain Hashmi
8/7/2019 JDBC lecture
2/28
2
Introduction to JDBCIntroduction to JDBC
JDBC is used for accessing databases
from Java applications
Information is transferred from relationsto objects and vice-versa
databases optimized for searching/indexing
objects optimized for engineering/flexibility
8/7/2019 JDBC lecture
3/28
3
JDBC ArchitectureJDBC Architecture
JavaApplication JDBC
MS AccessSQL Server
DB2
Oracle
Access
Driver
DB2
Driver
Oracle
Driver
These are
Java classes
Network
We willuse this one
8/7/2019 JDBC lecture
4/28
JDBC Architecture (cont.)JDBC Architecture (
cont.)
Application JDBC Driver
Java code calls JDBC library
JDBC loads a driver
Driver talks to a particular database
Can have more than one driver -> more than one
database
Ideal: can change database engines without changing
any application code
8/7/2019 JDBC lecture
5/28
5
JDBC DriversJDBC Drivers
Javaap
plication
JDBC-Driver manager
NativeAPI-driver
JDBC-ODBCbridge
Client libraryODBC
Client library
JDBC-API
8/7/2019 JDBC lecture
6/28
6
What is ODBC?What is ODBC?
ODBC is (Open Database Connectivity): A standard or open application programming
interface (API) for accessing a database.
By using ODBC statements (DSN, Data SourceName) in a program, you can access files in anumber of different databases, includingAccess, dBase, DB2, Excel, and Text.
ODBC handles the SQL request and converts itinto a request the individual database systemunderstands.
8/7/2019 JDBC lecture
7/287
Running a JDBC ApplicationRunning a JDBC Application
Phase Task Relevant java.sql classes
Initialisation
Processing
Termination
Load driverCreate connection
Generate SQL statements
Process result data
Terminate connectionRelease data structures
DriverManagerConnection
Statement
ResultSet etc.
ConnectionStatement etc.
8/7/2019 JDBC lecture
8/288
Seven StepsSeven Steps
Load the driver
Define the connection URL
Establish the connection Create a Statement object statement
Execute a query using statement Process the result
Close the connection
8/7/2019 JDBC lecture
9/289
Loading the DriverLoading the Driver
We can register the Driver indirectly using the
Java statement:Class.forName(sun.jdbc.odbc.JdbcOdbcDriver"); or
Class.forName(oracle.jdbc.driver.OracleDriver");
Calling Class.forName causes the Driver class to be
loaded
When this class is loaded, it automatically
creates an instance of itself
registers this instance with the DriverManager
8/7/2019 JDBC lecture
10/2810
Connecting to the DatabaseConnecting to the Database
Every database is identified by a URL
Given a URL, DriverManager is asked to
find the driver that can talk to thecorresponding database
DriverManager tries all registereddrivers, until a suitable one is found
8/7/2019 JDBC lecture
11/2811
Connecting to the DatabaseConnecting to the Database
Connection con = DriverManager.
getConnection("jdbc.odbc:Books,userName,password );
jdbc.odbc:Books URL
userName Login Name
Password Login Password
8/7/2019 JDBC lecture
12/28
Interaction with the DatabaseInteraction with the Database
We use Statement objects in order to
Extract data from the database
Update the database
Three different interfaces are used:
Statement, PreparedStatement, CallableStatement
All are interfaces, thus cannot be instantiated
They are created by the Connection
8/7/2019 JDBC lecture
13/2813
Querying with StatementQuerying with Statement
The executeQuery method returns a ResultSetobject representing the query result.
Will be discussed later
String queryStr ="SELECT * FROM Member " +
"WHERE Name = 'harry potter'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(queryStr);
8/7/2019 JDBC lecture
14/2814
Changing DB with StatementChanging DB with Statement
String deleteStr =DELETE FROM Member " +
"WHERE Name = harry potter";
Statement stmt = con.createStatement();
int delnum = stmt.executeUpdate(deleteStr);
executeUpdate is used for data manipulation: insert, delete, update,
create table, etc. (anything other than querying!)
executeUpdate returns the number of rows modified
8/7/2019 JDBC lecture
15/28
ResultSetResultSet
A ResultSet provides access to a table of datagenerated 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
8/7/2019 JDBC lecture
16/28
ResultSet MethodsResultSet 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
8/7/2019 JDBC lecture
17/28
ResultSet MethodsResultSet Methods
TypegetType(int columnIndex)
returns the given field as the given type
fields indexed starting at 1 (not 0)
TypegetType(String columnName)
same, but uses name of field
less efficient
int findColumn(String columnName)
looks up column index given column name
8/7/2019 JDBC lecture
18/28
ResultSet MethodsResultSet 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)
8/7/2019 JDBC lecture
19/28
ResultSet MethodsResultSet 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)
8/7/2019 JDBC lecture
20/2820
ResultSet ExampleResultSet Example
Statement stmt = con.createStatement();
ResultSet rs = stmt.
executeQuery("select name, age from Employees");
// Print the result
while(rs.next()) {
System.out.print(rs.getString(1) + :);
System.out.println(rs.getShort(age)+);}
8/7/2019 JDBC lecture
21/28
Null ValuesNull Values
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)
For example, getInt(column) will return 0if the value is either 0 or null!!
8/7/2019 JDBC lecture
22/28
22
ResultSet Meta-DataResultSet Meta-Data
ResultSetMetaData rsmd = rs.getMetaData();
int numcols = rsmd.getColumnCount();
for (int i = 1 ; i
8/7/2019 JDBC lecture
23/28
Mapping Java Types to SQLMapping Java Types to SQLTypesTypes
SQL type Java TypeCHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINY INT byte
SMALL INT short
INTEGER int
BIG INT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.DateTIME java.sql.Time
TIMESTAMP java.sql.Timestamp
8/7/2019 JDBC lecture
24/28
Database TimeDatabase Time
Times in SQL are notoriously non-standard 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
8/7/2019 JDBC lecture
25/28
25
Cleaning Up After YourselfCleaning Up After Yourself
Remember to close the Connections, Statements and ResultSets
rs.close();
stmt.close();
con.close();
8/7/2019 JDBC lecture
26/28
26
Dealing With ExceptionsDealing With Exceptions
Jdbc normaly throw ClassNotFoundException and SQLException like.
try {Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver);connection = DriverManager.getConnection(
url, username, password );
}catch (ClassNotFoundException cnfe) {
System.out.println(cnfe.getMessage());
}
8/7/2019 JDBC lecture
27/28
27
Dealing With ExceptionsDealing With Exceptions
An exception can have more exceptions in it.
catch (SQLException e) {while (e != null) {
System.out.println(e.getSQLState());
System.out.println(e.getMessage());
System.out.println(e.getErrorCode());e = e.getNextException();
}
}
8/7/2019 JDBC lecture
28/28
A Summary of JDBC applicationA Summary of JDBC application
loadDriver
getConnection
createStatement
execute(SQL)
Result handling
Lastexecution ?
closeStatment
closeConnection
no
yes
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(jdbc:odbc:Books,,);
stmt.close();
con.close();
while (resultSet.next()) {...
}
resultSet.close();
resultSet = statement.executeQuery(SELECT * FROM Authors");
statement = connection.createStatement();
Top Related