Database Reference
In-Depth Information
Beware of Class.forName()!
The example program Connect.java registers the JDBC driver like this:
Class . forName ( "com.mysql.jdbc.Driver" ). newInstance ();
You're supposed to be able to register drivers without invoking newInstance() , like so:
Class . forName ( "com.mysql.jdbc.Driver" );
However, that call doesn't work for some Java implementations, so be sure to use new
Instance() , or you may find yourself enacting the Java motto, “write once, debug ev‐
erywhere.”
Some JDBC drivers (Connector/J among them) permit you to specify the username and
password as parameters at the end of the URL. In this case, omit the second and third
arguments of the getConnection() call. Using that URL style, write the code that es‐
tablishes the connection in the example program like this:
// connect using username and password included in URL
Connection conn = null ;
String url = "jdbc:mysql://localhost/cookbook?user=cbuser&password=cbpass" ;
try
{
Class . forName ( "com.mysql.jdbc.Driver" ). newInstance ();
conn = DriverManager . getConnection ( url );
System . out . println ( "Connected" );
}
The character that separates the user and password parameters should be & , not ; .
Additional connection parameters. Connector/J does not support Unix domain socket file
connections, so even connections for which the hostname is localhost are made via TCP/
IP. To specify an explicit port number, add : port_num to the hostname in the connection
URL:
String url = "jdbc:mysql://127.0.0.1:3307/cookbook" ;
2.2. Checking for Errors
Problem
Something went wrong with your program, and you don't know what.
 
Search WWH ::




Custom Search