26.3.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 26.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://localhost/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 Statement
and
PreparedStatement
objects, as well as
retrieve metadata about the database. This is explained in the
following sections.