To connect using file DSN:
Code:
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dbFile = "c:/db1.mdb"; // database file name
String connectionString = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + dbFile + ";DriverID=22;READONLY=true}";
Connection connection = DriverManager.getConnection(connectionString ,"","");
}
catch (Exception e)
{
// error handling code
}
Using proper DSN, you have to set up the database as an ODBC source under windows. Then, connecting is simple:
Code:
String dsnName = "mydatabase"; // DSN name in windows
String url = "jdbc:odbc:" + dsnName;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connection = DriverManager.getConnection(dbURL, "","");
}
catch (Exception e)
{
// error handling code
}
In both cases I left the username and password for the database as empty strings. If you need to supply a username and password, just fill in the second and third parameters of DriverManager.getConnection with the actual username and password, respectively.
Implementing the various database functions is the same as with any other jdbc code. For example, to update a row in the mythical customer table:
Code:
int id = 1;
String name = "Tom";
String queryString = "UPDATE customer SET name = ? WHERE id = ?";
PreparedStatement statement = connection.preparesStatement(queryString);
statement.setString(1, name);
statement.setInt(2, id);
statement.execute();
connection.commit();
statement.close();
The other functions can be implemented similarly, with use of java.sql.PreparedStatement and java.sql.Statement. I'll let you figure them out.