JDBC
Intro To JDBC
JDBC stands for Java Database Connectivity, and it's the API supplied
by Sun for access to databases. The JDBC API is defined in two
packages: java.sql, and javax.sql. java.sql contains the "client" JDBC
API whereas javax.sql contains more server-oriented extensions, like
connection pooling. JDBC has gone through several revisions. The
current version is JDBC 3.0, but a lot of basic functionality has
remained the same since JDBC 1.0. JDBC provides a common API for
database access, regardless of the particular database server you're
using. It accomplishes this using a component-oriented architecture.
Database vendors (e.g. Oracle, SQL Server, Sybase, MySQL, PostgreSQL,
etc...) supply a driver for JDBC. Once you load the right driver,
you're off to the races and can continue working with just the JDBC
API. JDBC is a fairly thin interface, in that it allows you
mainly to send SQL statements to a particular database. If you are
interested in more generic object-relational mapping, take a look at
Hibernate (highly recommended) or JDO, or EJB. The basic features
of JDBC are:
- Retrieving data
- Creating data
- Transactions
Loading a JDBC Driver and Establishing a Connection
Loading a JDBC driver is done using reflection. You pass the name of
the driver class and the appropriate driver gets loaded for you by the
Java Runtime. This allows anyone to write a JDBC driver than can be
transparently loaded into an application. As long as you conform to the
interfaces, you too can write your own JDBC driver, say for a database
using simple files or a database that stores data in XML (acually, the
latter already exists I believe). For demo purposes, Sun supplies a
JDBC driver that connects to Microsoft's ODBC (if you want to connect a
real application to, say, SQL Server, don't use this driver. Use the
driver supplied by microsoft, or a commercial driver). The following
line of code will load the JDBC-ODBC bridge driver:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
To connect to an Oracle database using the Oracle Thin-Client JDBC
driver, try this:
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
or
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
To get a connection, you specify the name of the ODBC DSN, the
username, and the password:
Connection con = DriverManager.getConnection("jdbc:odbc:MyAccessDB, "sa", "mypassword");
The format of the first string will vary from driver to driver... For
example, here is the call using the Oracle Thin-Client JDBC Driver from
Oracle:
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@//myhost:1521/orcl",
"scott", "tiger");
Once you have a connection, you can use that connection to access the
database, i.e. send SQL command, and start/commit/rollback transactions!