Originally posted by Phil Hanna:
Here is an example of using the JDBC-ODBC bridge with a Microsoft Access database. You need to define a system data source name (DSN) first; I've defined one for the USDA nutrient database (USDA).
There is a "Getting Started" document in the JDK that is quite useful for getting up to speed on JDBC.
import java.io.*;
import java.sql.*;
import java.util.*;
public class JDBC_Sample
{
public static final String DRIVER_CLASS = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DSNAME = "usda";
public static void main(String[] args)
throws Exception
{
new JDBC_Sample();
}
public JDBC_Sample() throws ClassNotFoundException, SQLException
{
// Load the JDBC driver class
Class.forName(DRIVER_CLASS);
// Connect to the database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc dbc:" + DSNAME);
stmt = con.createStatement();
// Run a query
rs = stmt.executeQuery("select * from fd_groups");
while (rs.next()) {
String code = rs.getString(1);
String description = rs.getString(2);
System.out.println(code + " " + description);
}
}
finally {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
}
}
}