Working with Access thru Java


Database Connectivity

Setting up ODBC

Now that you have the ODBC control panel applet open, you should be presented with the following information:

Next you have to add a data source that the JDBC-ODBC Bridge driver can open.

To do so, click add.

The following dialog will now appear:

Make sure you select “Microsoft Access Driver” as shown above and click finish.

In the next screen enter a name for your data source – this is the name you will use in your Java code to open your database. Also enter a description. Use the “Select” button to browse for your database on your PC.

Below is what you should now have:

Click Ok. Your database will now be in the list of data sources:

Java

In your Java application, make sure you include the java.sql package.

Here is some sample code:


import java.sql.*;

public class Temp {

public static void main(String args[]) {

Connection con; // The connection to the database.
// The following code can throw errors, so they must be caught.
try{

    // First, tell Java what driver to use and where to find it.
    Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
    // Next, create a connection to your data source.
    // Specify that you are using the ODBC-JDBC Bridge.
    // And specify the data source from ODBC.

    con = DriverManager.getConnection(“jdbc:odbc:Temp”);
    // Create an SQL statement.
    Statement stmt = con.createStatement();
    // Execute some SQL to create a table in your database.
    // If the table already exists, an exception is thrown!

    stmt.executeUpdate(“CREATE TABLE COFFEES “ +
    “(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, “ +
    “SALES INTEGER, TOTAL INTEGER)”);

}
// Catch any exceptions that are thrown.
catch(ClassNotFoundException e){

    System.out.println(e.toString());

}
catch(SQLException e){

    System.out.println(e.toString());

}

}

}


The following screen shot shows that the above code did infact create the table specified by the SQL:

Advertisements