AJPChapter3PPT JDBC
AJPChapter3PPT JDBC
17-Sep-08
JDBC
JDBC is a Sun trademark
It is often taken to stand for Java Database Connectivity
Java is very standardized, but there are many versions
of SQL
JDBC is a means of accessing SQL databases from Java
JDBC is a standardized API for use by Java programs
JDBC is also a specification for how third-party vendors
should write database drivers to access specific SQL versions
Driver types
There are four types of drivers:
JDBC Type 1 Driver -- JDBC/ODBC Bridge drivers
ODBC (Open DataBase Connectivity) is a standard software API
designed to be independent of specific programming languages
Sun provides a JDBC/ODBC implementation
JDBC Type 2 Driver -- use platform-specific APIs for data
access
JDBC Type 3 Driver -- 100% Java, use a net protocol to
access a remote listener and map calls into vendor-specific
calls
JDBC Type 4 Driver -- 100% Java
Most efficient of all driver types
Connector/J
Connector/J is a JDBC Type 4 Driver for connecting
Java to MySQL
Installation is very simple:
Download the “Production Release” ZIP file from
http://dev.mysql.com/downloads/connector/j/3.1.html
Unzip it
Put the JAR file where Java can find it
Add the JAR file to your CLASSPATH, or
In Eclipse: Project --> Properties --> Java Build Path -->
Libraries --> Add External Jars...
Connecting to the server
First, make sure the MySQL server is running
In your program,
import java.sql.Connection; // not com.mysql.jdbc.Connection
import java.sql.DriverManager;
import java.sql.SQLException;
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
Example, continued
while (rs.next ()) {
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
Prepared statements
Prepared statements are precompiled, hence much more
efficient to use
PreparedStatement s;
s = conn.prepareStatement (
"INSERT INTO animal (name, category VALUES(?,?)");
s.setString (1, nameVal);
s.setString (2, catVal);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
Error handling
try {
Statement s = conn.createStatement ();
s.executeQuery ("XYZ"); // issue invalid query
s.close ();
}
catch (SQLException e) {
System.err.println ("Error message: "
+ e.getMessage ());
System.err.println ("Error number: "
+ e.getErrorCode ());
}
The End