1. MySQL Connector/J
_________________________________________________________________
MySQL provides connectivity for client applications developed in the Java
programming language via a JDBC driver, which is called MySQL Connector/J.
MySQL Connector/J is a JDBC-3.0 "Type 4" driver, which means that is is pure
Java, implements version 3.0 of the JDBC specification, and communicates
directly with the MySQL server using the MySQL protocol.
This document is arranged for a beginning JDBC developer. If you are already
experienced with using JDBC, you might consider starting with the section
"[1]Installing Connector/J".
While JDBC is useful by itself, we would hope that if you are not familiar
with JDBC that after reading the first few sections of this manual, that you
would avoid using "naked" JDBC for all but the most trivial problems and
consider using one of the popular persistence frameworks such as Hibernate
(http://www.hibernate.org/), Spring's JDBC templates
(http://www.springframework.org/) or Ibatis SQL Maps
(http://www.ibatis.com/common/sqlmaps.html) to do the majority of repetitive
work and heavier lifting that is sometimes required with JDBC.
This section is not designed to be a complete JDBC tutorial. If you need
more information about using JDBC you might be interested in the following
online tutorials that are more in-depth than the information presented here:
* JDBC Basics
(http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html)- A
tutorial from Sun covering beginner topics in JDBC
* JDBC Short Course
(http://java.sun.com/developer/onlineTraining/Database/JDBCShortCourse/i
ndex.html) - A more in-depth tutorial from Sun and JGuru
1.1. Basic JDBC concepts
This section provides some general JDBC background.
1.1.1. Connecting to MySQL using the DriverManager Interface
When you are using JDBC outside of an application server, the DriverManager
class manages the establishment of Connections.
The DriverManager needs to be told which JDBC drivers it should try to make
Connections with. The easiest way to do this is to use Class.forName() on
the class that implements the java.sql.Driver interface. With MySQL
Connector/J, the name of this class is com.mysql.jdbc.Driver. With this
method, you could use an external configuration file to supply the driver
class name and driver parameters to use when connecting to a database.
The following section of Java code shows how you might register MySQL
Connector/J from the main() method of your application:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
After the driver has been registered with the DriverManager, you can obtain
a Connection instance that is connected to a particular database by calling
DriverManager.getConnection():
Example 1. Obtaining a Connection From the DriverManager
This example shows how you can obtain a Connection instance from the
DriverManager. There are a few different signatures for the getConnection()
method. You should see the API documentation that comes with your JDK for
more specific information on how to use them.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
... try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localho
st/test?user=monty&password=greatsqldb");
// Do something with the Connection
....
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
Once a Connection is established, it can be used to create Statements and
PreparedStatements, as well as retrieve metadata about the database. This is
explained in the following sections.
1.1.2. Using Statements to Execute SQL
Statements allow you to execute basic SQL queries and retrieve the results
through the ResultSet class which is described later.
To create a Statement instance, you call the createStatement() method on the
Connection object you have retrieved via one of the
DriverManager.getConnection() or DataSource.getConnection() methods
described earlier.
Once you have a Statement instance, you can execute a SELECT query by
calling the executeQuery(String) method with the SQL you want to use.
To update data in the database use the executeUpdate(String SQL) method.
This method returns the number of rows affected by the update statement.
If you don't know ahead of time whether the SQL statement will be a SELECT
or an UPDATE/INSERT, then you can use the execute(String SQL) method. This
method will return true if the SQL query was a SELECT, or false if an
UPDATE/INSERT/DELETE query. If the query was a SELECT query, you can
retrieve the results by calling the getResultSet() method. If the query was
an UPDATE/INSERT/DELETE query, you can retrieve the affected rows count by
calling getUpdateCount() on the Statement instance.
Example 2. Using java.sql.Statement to Execute a SELECT Query
// assume conn is an already created JDBC connection
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT foo FROM bar");
// or alternatively, if you don't know ahead of time that
// the query will be a SELECT...
if (stmt.execute("SELECT foo FROM bar")) {
rs = stmt.getResultSet();
}
// Now do something with the ResultSet ....
} finally {
// it is a good idea to release
// resources in a finally{} block
// in reverse-order of their creation
// if they are no-longer needed
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { // ignore }
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { // ignore }
stmt = null;
}
}
1.1.3. Using CallableStatements to Execute Stored Procedures
Starting with MySQL server version 5.0 when used with Connector/J 3.1.1 or
newer, the java.sql.CallableStatement interface is fully implemented with
the exception of the getParameterMetaData() method.
MySQL's stored procedure syntax is documented in the "Stored Procedures and
Functions (http://www.mysql.com/doc/en/Stored_Procedures.html)" section of
the MySQL Reference Manual.
Connector/J exposes stored procedure functionality through JDBC's
CallableStatement interface.
The following example shows a stored procedure that returns the value of
inOutParam incremented by 1, and the string passed in via inputParam as a
ResultSet :
Example 3. Stored Procedure Example
CREATE PROCEDURE demoSp(IN inputParam VARCHAR(255), INOUT inOutParam INT)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inputParam;
SELECT CONCAT('zyxw', inputParam);
END
To use the demoSp procedure with Connector/J, follow these steps:
1. Prepare the callable statement by using Connection.prep
- 1
- 2
- 3
- 4
- 5
- 6
前往页