For connect ions t o localhost , you can provide a
unix_socket
param et er t o specify t he pat h t o t he Unix dom ain socket :
conn = MySQLdb.connect db = cookbook, host = localhost,
unix_sock = vartmpmysql.sock, user = cbuser,
passwd = cbpass
For non- localhost connect ions, you can provide a
port
param et er t o specify t he port num ber: conn = MySQLdb.connect db = cookbook,
host = mysql.snake.net, port = 3307,
user = cbuser, passwd = cbpass
2.2.7 Java
Dat abase program s in Java are writ t en using t he JDBC int erface, in conj unct ion wit h a driver for t he part icular dat abase engine you wish t o access. This m akes t he JDBC archit ect ure
sim ilar t o t hat used by t he Perl DBI and Pyt hon DB- API m odules: a generic int erface used in conj unct ion wit h dat abase- specific drivers. Java it self is sim ilar t o Pyt hon in t hat you dont t est
specific funct ion calls for ret urn values t hat indicat e an error. I nst ead, you provide handlers t hat are called when except ions are t hrown.
Java program m ing requires a soft ware developm ent kit SDK . See t he sidebar, I nst alling a
Java SDK for inst ruct ions on inst alling one if you need it . To writ e MySQL- based Java
program s, youll also need a MySQL- specific JDBC driver. Several are list ed in Appendix A
. I use t he MySQL Connect or J driver because it is free and is act ively m aint ained; use one of t he
ot her drivers if you prefer. MySQL Connect or J is t he successor t o MM.MySQL, and if you already have MM.MySQL inst alled, you can use it inst ead by m aking a sim ple change:
whenever you see
org.gjt.mm.mysql
in Java code, replace it wit h
com.mysql.jdbc
.
Installing a Java SDK
j ava.sun.com m akes Java SDKs available for Solaris, Linux, and Windows, but you m ay already have t he necessary t ools inst alled, or t hey m ay be available by anot her
m eans. For exam ple, Mac OS X includes j avac, j ikes, and ot her support needed for building Java applicat ions in t he Developer Tools dist ribut ion available at
connect .apple.com . I f a Java SDK is not already inst alled on your syst em , get one from j ava.sun.com ,
inst all it , and set t he
JAVA_HOME
environm ent variable t o t he pat hnam e where t he SDK is inst alled. Exam ples shown here assum e an SDK inst allat ion direct ory of
usr local j ava j dk for Unix and D: \ j dk for Windows, so t he com m ands for set t ing
JAVA_HOME
look like t his: export JAVA_HOME=usrlocaljavajdk
sh, bash, etc. setenv JAVA_HOME=usrlocaljavajdk
csh, tcsh, etc. set JAVA_HOME=D:\jdk
Windows Adj ust t he inst ruct ions appropriat ely for t he pat hnam e used on your syst em . To
m ake environm ent variable changes t ake effect , log out and log in again under Unix, or rest art under Windows. For m ore inform at ion on set t ing environm ent variables,
see Recipe 1.9
. The following Java program , Connect .j ava, illust rat es how t o connect t o and disconnect from
t he MySQL server: Connect.java - connect to the MySQL server
import java.sql.; public class Connect
{ public static void main String[ ] args
{ Connection conn = null;
String url = jdbc:mysql:localhostcookbook; String userName = cbuser;
String password = cbpass; try
{ Class.forName com.mysql.jdbc.Driver.newInstance ;
conn = DriverManager.getConnection url, userName, password; System.out.println Connected;
} catch Exception e
{ System.err.println Cannot connect to server;
} finally
{ if conn = null
{ try
{ conn.close ;
System.out.println Disconnected; }
catch Exception e { ignore close errors } }
} }
}
The
import java.sql.
st at em ent references t he classes and int erfaces t hat provide access t o t he dat a t ypes you use t o m anage different aspect s of your int eract ion wit h t he dat abase
server. These are required for all JDBC program s. Connect ing t o t he server is a t wo-st ep process. First , regist er t he dat abase driver wit h JDBC
by calling
Class.forName
. Then call
DriverManager.getConnection
t o init iat e t he connect ion and obt ain a
Connection
obj ect t hat m aint ains inform at ion about t he st at e of t he connect ion. Java program s in t his book convent ionally use
conn
t o signify connect ion obj ect s.
Use
com.mysql.jdbc.Driver
for t he nam e of t he MySQL Connect or J JDBC driver. I f you use a different driver, check it s docum ent at ion and use t he nam e specified t here.
DriverManager.getConnection
t akes t hree argum ent s: a URL describing where t o connect and t he dat abase t o use, t he MySQL usernam e, and t he password. The form at of t he
URL st ring is as follows: jdbc:
driver
:
host_name db_name
This form at follows t he usual Java convent ion t hat t he URL for connect ing t o a net work resource begins wit h a prot ocol designat or. For JDBC program s, t he prot ocol is
jdbc
, and youll also need a subprot ocol designat or t hat specifies t he driver nam e
mysql
, for MySQL program s . Many part s of t he connect ion URL are opt ional, but t he leading prot ocol and
subprot ocol designat ors are not . I f you om it
host_name
, t he default host value is
localhost
. I f you om it t he dat abase nam e, no dat abase is select ed when you connect . However, you should not om it any of t he slashes in any case. For exam ple, t o connect t o t he
local host wit hout select ing a dat abase nam e, t he URL is: jdbc:mysql:
To t ry out t he program , you should com pile it and execut e it . The
class
st at em ent indicat es t he program s nam e, which in t his case is
Connect
. The nam e of t he file cont aining t he program should m at ch t his nam e and include a .j ava ext ension, so t he filenam e for t he
exam ple program is Connect .j ava.
[ 1]
Com pile t he program using j avac:
[ 1]
I f you m ake a copy of Connect .j ava t o use as t he basis for a new program , youll need t o change t he class nam e in t he
class
st at em ent t o m at ch t he nam e of your new file.
javac Connect.java
I f you prefer a different Java com piler, j ust subst it ut e it s nam e in com pilat ion com m ands. For exam ple, if youd rat her use Jikes, com pile t he file like t his inst ead:
jikes Connect.java
j avac or j ikes, or what ever generat es com piled byt e code t o produce a class file nam ed Connect .class. Use t he j ava program t o run t he class file not e t hat you specify t he nam e of
t he class file wit hout t he .class ext ension :
java Connect Connected
Disconnected
You m ay need t o set your
CLASSPATH
environm ent variable before t he exam ple program will com pile and run. The value of
CLASSPATH
should include at least your current direct ory
.
and t he pat h t o t he MySQL Connect or J JDBC driver. On m y syst em , t hat driver is locat ed in usr local lib j ava lib m ysql- connect or- j ava-bin.j ar, so for t csh or csh, I d set
CLASSPATH
like t his:
setenv CLASSPATH .:usrlocallibjavalibmysql-connector-java-bin.jar For shells such as sh, bash, and ksh, I d set it like t his:
export CLASSPATH=.:usrlocallibjavalibmysql-connector-java-bin.jar Under Windows, I d set
CLASSPATH
as follows if t he driver is in t he D: \ Java\ lib direct ory: CLASSPATH=.;D:\Java\lib\mysql-connector-java-bin.jar
You m ay also need t o add ot her class direct ories or libraries t o your
CLASSPATH
set t ing; t he specifics depend on how your syst em is set up.
Beware of Class.forName
The exam ple program Connect .j ava regist ers t he JDBC driver like t his: Class.forName com.mysql.jdbc.Driver.newInstance ;
Youre supposed t o be able t o regist er drivers wit hout invoking
newInstance
, like so:
Class.forName com.mysql.jdbc.Driver; However, t hat call doesnt work for som e Java im plem ent at ions, so be sure not t o
om it
newInstance
, or you m ay find yourself enact ing t he Java m ot t o, writ e once, debug everywhere.
Som e JDBC drivers MySQL Connect or J am ong t hem allow you t o specify t he usernam e and password as param et ers at t he end of t he URL. I n t his case, you om it t he second and t hird
argum ent s of t he
getConnection
call. Using t hat URL st yle, t he code t hat est ablishes t he connect ion in t he exam ple program could have been writ t en like t his:
connect using username and password included in URL Connection conn = null;
String url = jdbc:mysql:localhostcookbook?user=cbuserpassword=cbpass; try
{ Class.forName com.mysql.jdbc.Driver.newInstance ;
conn = DriverManager.getConnection url; System.out.println Connected;
}
The charact er t hat separat es t he
user
and
password
param et ers should be , not
;
.
2 .2 .7 .1 Addit ion a l con n e ct ion pa r a m e t e r s
For non- localhost connect ions, specify an explicit port num ber by adding
: port_num
t o t he host nam e in t he connect ion URL:
String url = jdbc:mysql:mysql.snake.net:3307cookbook; For connect ions t o localhost , t here is no opt ion for specifying t he Unix dom ain socket
pat hnam e, at least not for MySQL Connect or J. Ot her MySQL JDBC drivers m ay allow for t his; check t heir docum ent at ion.
2.3 Checking for Errors