* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Programming with Java
Survey
Document related concepts
Transcript
Programming
with Java
Introduction to JDBC
Instructor: Daniel J. Hood
Northrop Grumman Corporation
1
Overview
What is JDBC?
JDBC Architecture
JDBC API
JDBC Drivers
A JDBC Example
Loading the Driver
Opening/Closing a Connection
Creating/Closing a Statement
Getting a ResultSet
Object-Relational Mapping Tools
What is JDBC
Stands for Java DataBase Connectivity
API consisting of Java classes, interfaces, exceptions and a
specification which driver vendors adhere to
java.sql
javax.sql
JDBC is Sun's attempt to create a platform neutral interface
between various databases and the Java language
Isolates program from database details
For the most part you will use Interfaces defined in java.sql and
javax.sql, and the vendor specified JDBC driver will provide
classes which implement those interfaces
So, if you are programming to an interface it should be trivial to
change the underlying driver without breaking anything.
3
JDBC Architecture
4
JDBC API
DriverManager
Loads JDBC driver into JVM
Used to obtain connections to a DataSource
Connection
Represents a connection with a DataSource
Used to create Statement, PreparedStatement and
CallableStatement objects.
Statement
Represents a static SQL statement.
Can be used to retrieve ResultSet objects.
PreparedStatement
Higher performance alternative to Statement object,
represents a precompiled SQL statement.
5
JDBC API (continued)
CallableStatement
Represents a stored procedure. Can be used to
execute stored procedures in a RDBMS which
supports them.
ResultSet
Represents a database result set generated by using
a SELECT SQL statement.
SQLException
An exception class which encapsulates database
base access errors.
DataSource
Abstracts a data source. This object can be used in
place of DriverManager to efficiently obtain data
source connections
6
JDBC Drivers
Type 1 JDBC-ODBC bridge drivers
Sits atop preexisting ODBC setup
Type 2 Native-API partly Java drivers
Uses native API as basis (wrapped via JNI)
Type 3 Net-protocol All-Java drivers
100% Java
Connect to another machine which talks to the DB in
some fashion
Type 4 Native-protocol All-Java drivers
100% Java
“Best” solution when available
7
Obtaining a Driver for Your Database
Each vendor must provide a JDBC driver to talk to their
database
Typically the JDBC driver is distributed as a jarfile that needs to
be added to the classpath
Various vendors JDBC Drivers
MySQL
http://dev.mysql.com/downloads/connector/j/
Oracle
http://www.oracle.com/technology/software/tech/java/sqlj_j
dbc/
PostgreSQL
http://jdbc.postgresql.org/
Sybase
http://www.sybase.com/detail_list?id=11662&multi=true&S
R=Y&show=1265
MS Access
JDBC-ODBC Driver
Loading the Driver
The driver we are using will need to be registered with
the JDBC DriverManager
Typically done via loading the class directly
Class.forName(“com.oracle.jdbc.OracleDriver”);
This method may throw a ClassNotFoundException,
so we must wrap it in a try/catch block
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.err.println("Failed to load the JDBC driver");
}
9
JDBC URLs
JDBC drivers use a JDBC URL to identify and connect
to a given database
Typically specify
Driver name
Machine to connect to
Database name
Username (typically optional)
Password (typically optional)
General format like so:
jdbc:driver:databasename
10
Connecting to the Database
To connect to the database we need to get a
connection off of the DriverManager
Connection conn = DriverManager.getConnection("url", "user", "password");
We should also take some care to close the
connection when we are done with it to free up
resources
11
Connecting to the Database (continued)
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test","username","password");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("Failed to load the JDBC driver");
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.err.println("Failed to close the connection.");
}
}
}
12
Creating a Statement
The next thing that we need to do is to create a SQL
Statement to issue to the database
There are 3 different types of statements that are
supported
Statement
A basic SQL statement
PreparedStatement
A precompiled SQL statement
CallableStatement
Access to stored procedures
Just like a connection, we should close the statement
when we are done with it
13
Creating a Statement (continued)
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test","username","password");
statement = connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("Failed to load the JDBC driver");
}
// continued on next slide
Creating a Statement (continued)
// continued from previous slide
finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
System.err.println("Failed to close the statement.");
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.err.println("Failed to close the connection.");
}
}
}
Obtaining a ResultSet
We can get a ResultSet back which represents the
results of our query
A ResultSet is returned from executing a query
statement.executeQuery("select * from people");
You can think of a result set as an iterator over a
collection of results that you can walk through
next() – returns a boolean if there is more data and
advances to the next item in the collection
There are a lot of methods to get data out of the results
set in the following format
getType(int colNum)
getType(String colName)
i.e. String name = rs.getString(“first”);
16
Obtaining a ResultSet (continued)
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test","username","password");
statement = connection.createStatement();
ResultSet results =
statement.executeQuery("select * from people");
while (results != null && results.next()) {
System.out.println(results.getString("first") + " " +
results.getString("last") );
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.err.println("Failed to load the JDBC driver");
}
// continued on next slide
Obtaining a ResultSet (continued)
// continued from previous slide
finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
System.err.println("Failed to close the statement.");
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.err.println("Failed to close the connection.");
}
}
}
Execution
For the following database table
mysql> select * from people;
+-------+-------+
| first | last |
+-------+-------+
| John | Doe
|
| Jane | Smith |
+-------+-------+
2 rows in set (0.00 sec)
Our code produces
John Smith
Jane Doe
Object-Relational Mapping Tools
In recent years there has been a lot of work to reduce the
complexity of manually writing the SQL code to map Java
objects to a table in the database
Tools like Hibernate (http://www.hibernate.org/) provide a
framework for persisting Plain Old Java Objects (POJOs) to a
relational database
Typically all you need to configure is the following:
Where the database is and who to connect as
What JDBC driver to use
Which Java objects map to which tables
Which members map to which columns
This way you can write simple Java Bean classes and hand
them off to a framework such as hibernate to persist them to the
database
The framework manages all SQL – no SQL in your code
20