Академический Документы
Профессиональный Документы
Культура Документы
This article explains how to use the JDBC ODBC bridge to access an MS-Access database from
Java applications. Instead of elaborating on the basics of the database, let's get down to the
subject.
ODBC driver
In Java, we require a driver to be loaded at runtime to connect to any data source. The same is
the case for ODBC data sources too. The driver is implemented as a class that is located and
loaded at runtime. The ODBC driver for JDBC connections is named
sun.java.odbc.JdbcOdbcDriver.
In Java, we would write a similar connection string, but there would be an additional
specification that points to the driver that will be required for the connection, that is,
jdbc:odbc:. Then, follow it up with the connection string. So the connection string in Java
becomes:
Collapse | Copy Code
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=myDB.mdb;"
Thus, to generalize the above, to be able to connect with an ODBC DSN, we require a
connection string of the form:
Collapse | Copy Code
"jdbc:odbc:ODBC DSN String"
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!=null) && (rs.next()))
{
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
That's all. Let us now see a demo app that clarifies all that I have written above.
An example application
The following application does the following:
1. Loads the JDBC ODBC driver.
2. Opens a ODBC data source which opens the file myDB.mdb present in the application
working directory.
3. Gets the Statement object for SQL execution.
4. Generates the name of a table with a random number generator.
5. Creates the table.
6. Enters 25 random entries into it.
7. Displays the content of the table.
8. Deletes or drops the table created.
9. Closes the Statement object and then closes the connection to the database.
Here is the required code:
Collapse | Copy Code
/* Program:
*
Setup database driver manager to understand and use ODBC MS-ACCESS data
source.
* Written by Arnav Mukhopadhyay (ARNAV.MUKHOPADHYAY@smude.edu.in)
* Compile as: javac dbAccess.java
*/
import java.sql.*;
public class dbAccess
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database =
"jdbc:odbc:Driver={Microsoft Access Driver
(*.mdb)};DBQ=myDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement();
// create a table