1. JDBC
Jussi
Pohjolainen
Tampere
University
of
Applied
Sciences
2. JDBC
Intro
• Java
Database
Connec@vity
in
Java
since
1.1
• API
in
Java
for
accessing
Databases
• PlaDorm
independent,
Database
independent
3. Drivers
• To
access
a
database,
you
need
a
driver
• To
code
in
Java
is
always
the
same,
changing
the
driver
changes
the
connec@on
to
different
database.
• Lot’s
of
drivers
for
different
databases:
MySQL,
Text,
MS
SQL
Server..
4. Driver
Types
• JDBC
Drivers
are
divided
into
four
categories
– Type
1
that
calls
na@ve
code
of
the
locally
available
ODBC
driver.
– Type
2
that
calls
database
vendor
na.ve
library
on
a
client
side.
– Type
3,
the
pure-‐java
driver
that
talks
with
the
server-‐side
middleware
that
then
talks
to
database.
– Type
4,
the
pure-‐java
driver
that
uses
database
na@ve
protocol.
• In
most
cases
you
can
access
the
same
database
with
four
different
type
of
drivers
• List
of
drivers:
– hQp://developers.sun.com/product/jdbc/drivers
5. To
use
JDBC
1. Register
driver
2. Access
database
3. Do
some
SQL
magic
4. Handle
result
5. Close
the
connec@on
6. 1.
Register
the
Driver
try {
// The driver string here is given you by the
// driver documentation.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(ClassNotFoundException e) {
System.out.println(”Can’t find the driver!");
}
10. Handle
Result?
• In
previous
example,
the
result
of
the
SQL
was
boolean
value
(we
did
not
handle
it).
• If
SQL
is
select,
then
you
can
retrieve
the
results
• Use
ResultSet
object.
ResultSet
holds
the
result
of
your
SQL
query
• You
can
navigate
in
result
set
13. ResultSetMetaData
• Don’t
know
column
names?
Or
amount?
• You
can
check
these
using
ResultSetMetaData
• Example
usage:
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount ();
while (rs.next()) {
for (int i=1; i<=numCols; i++) {
System.out.println(rs.getString(i));
}
}
14. Transac@ons
• If
you
want
to
commit
several
sql
–
commands
into
one:
– conn.setAutoCommit(false);
– // do some sql
– conn.commit();
– conn.rollback();
15. Prepared
Statements
• Prepared
statement
or
parameterized
statement
is
a
feature
used
to
execute
the
same
or
similar
database
statements
repeatedly
with
high
efficiency.
• Example
Connection con = connect();
String sql = "UPDATE table1 set one = ?, two = ?";
PreparedStatement preStmt = con.prepareStatement(sql);
preStmt.setInt(1, 123);
preStmt.setString(2, "myNewValue2");
preStmt.executeUpdate();
19. Update
Result
• It’s
possible
to
update
the
result
using
methods
– updateString()
– updateInt()
– updateFloat()..
• Once
updated,
call
updateRow(),
which
will
move
the
result
to
database