Connecting to a Database via JDBC


Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn =    DriverManager.getConnection(url, user, password);



To make a database connection using JDBC, you first have to load a driver. In this phrase, we load the JdbcOdbcDriver. This driver provides connectivity to an ODBC data source. We load the driver using the Class.forName() method. Database JDBC drivers are generally provided by database vendors, although Sun does provide several generic drivers such as the ODBC driver that we use in this phrase. After we have the driver loaded, we get a connection to the database using the DriverManager.getConnection() method. We use a URL-like syntax to specify the database that you want to connect to. We also pass valid database login name and password. The URL must begin with the prefix jdbc:. After the prefix, the remainder of the URL specification format is vendor specific. The URL syntax for connecting to an ODBC database is shown here:

jdbc:odbc:databasename

Most drivers will require the URL string to include a hostname, a port, and a database name. For example, here is a valid URL for connecting to a MySQL database:

jdbc:mysql://db.myhost.com:3306/mydatabase

This URL specifies a MySQL database on the host db.myhost.com, connecting on port 3306, with the database name of mydatabase. The general format for a MySQL database URL is as follows:

jdbc:mysql://host:port/database

An alternative way of obtaining a database connection is through the use of JNDI. This is the approach you'd typically take if you were using an application server such as BEA WebLogic or IBM WebSphere.

Hashtable ht = new Hashtable(); ht.put(Context.INITIAL_CONTEXT_FACTORY,      "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL, "t3://hostname:port"); Context ctx = new InitialContext(ht); javax.sql.DataSource ds =   (javax.sql.DataSource) ctx.lookup ("myDataSource"); Connection conn = ds.getConnection();


When using JNDI, we create an InitialContext instance and use that to look up a DataSource. We then get the connection from the data source object. There is also a version of the getConnection() method available that allows you to pass a user name and password to the database to get the connection for a database requiring user authentication.

It is important to always close a connection using the Connection class's close() method when you are finished using the Connection instance.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net