Java Reference
In-Depth Information
To connect to a data source and obtain a Connection instance, call one of
DriverManager 's Connection getConnection(String url) , Connec-
tion getConnection(String url, Properties info) , or Connec-
tion getConnection(String url, String user, String pass-
word) methods. Witheither method, the url argument specifies astring-based URL
that starts with the jdbc: prefix and continues with data source-specific syntax.
ConsiderJavaDB.TheURLsyntaxvariesdependingonthedriver.Fortheembedded
driver (when you want to access a local database), this syntax is as follows:
jdbc:derby: databaseName ; URLAttributes
For the client driver (when youwant to access a remote database, although youcan
also access a local database with this driver), this syntax is as follows:
jdbc:derby:// host : port / databaseName ; URLAttributes
With either syntax, URLAttributes isanoptional sequence ofsemicolon-delim-
ited name = value pairs. Forexample, create=true tells Java DBtocreate anew
database.
ThefollowingexampledemonstratesthefirstsyntaxbytellingJDBCtoloadtheJava
DB embedded driver and create the database named testdb on the local host:
Connection con = DriverMan-
ager.getConnection("jdbc:derby:testdb;create=true");
Thefollowing example demonstrates thesecondsyntaxbytelling JDBCtoloadthe
JavaDBclientdriverandcreatethedatabasenamed testdb onport 8500 ofthe xyz
host:
Connection con;
con = DriverManager.getConnection("jdbc:derby://xyz:8500/
testdb;create=true");
Note Forconvenience,thischapter'sapplicationsuseonlytheembeddeddrivercon-
nection syntax.
Exceptions
DriverManager 's getConnection() methods (and other JDBC methods in the
variousJDBCinterfaces)throw java.sql.SQLException oroneofitssubclasses
when something goes wrong. Along with the methods it inherits from
java.lang.Throwable (e.g., String getMessage() ), SQLException de-
clares various constructors (not discussed for brevity) and the following methods:
Search WWH ::




Custom Search