Once your environment is all set up, you are ready
to start sending SQL commands to your database using JDBC.
To do so, you will need to first connect to the database,
which is a fairly simple process. Specifically, you will need to
load the database driver and then request a connection.
These two things are achieved with the
following lines of code:
Class.forName([LOCATION OF DRIVER]);
Connection jdbcConnection =
DriverManager.getConnection
([LOCATION OF DATASOURCE]);
For example, to connect to my Access
(I specified the "Access" DataSource Name in the 32-bit ODBC
control panel. The name "Access" corresponds to my
Test_db.mdb file created by MsAccess) datasource I use the
following:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection jdbcConnection =
DriverManager.getConnection
(jdbc:odbc:Access);
Note that the JdbcOdbcDriver is part of the
basic JDK distribution (You can find it in the classes.zip file
in the "lib" directory probably). If you are using a driver other than
ODBC, you should check to see what syntax it requires for specifying
data source name. mSQL, for example, uses something like
Connection jdbcConnection =
DriverManager.getConnection
(jdbc:msql://hostname:9999/test_db");
Preparing a Statement Object
After you have setup a connection to the
database, you will need to instantiate a statement object that
you can use to pass SQL back and forth between the database
and your application. Creating a statement object is simple and
follows the form:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection jdbcConnection =
DriverManager.getConnection
(jdbc:odbc:Access);
Statement sql = jdbcConnection.createStatement();