Click here to Skip to main content
Click here to Skip to main content

Access MS-Access Databases from Java

By , 6 Apr 2009
 

Introduction

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.

ODBC connection string

As in Visual C++, we require an ODBC connection string to connect to the data source. Consider for example, that we are writing a VC++ program that connects to an Access database file named myDB.mdb present in the application directory. We would use an ODBC connection string as follows:

"Driver={Microsoft Access Driver (*.mdb)};DBQ=myDB.mdb;"

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:

"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:

"jdbc:odbc:ODBC DSN String"

Import the classes to connect to the database

The package containing the database related classes is contained in java.sql. So, we do the import as follows:

import java.sql.*;

Load the JDBC:ODBC driver

Dynamically load the class sun.java.odbc.JdbcOdbcDriver as follows:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Open the MS-Access database file in the application space

To do this, we use the ODBC DSN as specified above:

String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=myDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");

Create a Statement object to execute the SQL query

The Statement must be created to execute a SQL query on the opened database. It is done with the following code:

Statement s = conn.createStatement();

Cleanup after finishing the job

To clean up after we are done with the SQL query, we call s.close() to dispose the object Statement. Then, before we end our program or after the point where we decide that the database is not required any more, we close the database with a call to conn.close(). The following code does the cleanup after we are done:

s.close();  // Close the statement
conn.close(); // Close the database. Its no more required

Execute a SQL statement on a valid Statement object

Call s.execute("SQL statement") when you require to execute a SQL query. It returns the number of rows effected by the query. If the last query holds a ResultSet to be returned which generally occurs with SELECT ... type queries, then call s.getResultSet() which returns the ResultSet object. The following code shows how to use a SELECT query and display the value contained in the first two columns of the table.

String selTable = "SELECT * FROM SOMETABLE";
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:

/* 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
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable); 
            
            // enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }
            
            // Fetch table
            String selTable = "SELECT * FROM " + tableName;
            s.execute(selTable);
            ResultSet rs = s.getResultSet();
            while((rs!=null) && (rs.next()))
            {
                System.out.println(rs.getString(1) + " : " + rs.getString(2));
            }
            
            // drop the table
            String dropTable = "DROP TABLE " + tableName;
            s.execute(dropTable);
            
            // close and cleanup
            s.close();
            conn.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

That's all I have!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

arnavguddu
Other Student
India India
Member
http://gudduarnav.eu5.org/

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionAccess MS-Access Databases from Java - Great Postmemberboss prabu20 Apr '13 - 1:29 
Nice arnavguddu!! Even this http://www.compiletimeerror.com/2013/03/ms-access-database-connectivity-in-java.html[^] is helpful, Have a look, may help...
Generalaccessmembersuriyaleka15 Aug '12 - 21:08 
fine.. i ask everyone that how to use java with access. it is very useful for me.
QuestionAccess MS-Access Databases from Javamemberchathud22 Feb '12 - 10:35 
How to connect Access Database using Java
 
Connect to Access Database in Java
GeneralProblemmemberhusseinx7 Jul '10 - 6:19 

 
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=User.mdb;";
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Could not find file '(unknown)'.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3073)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Main.main(Main.java:11)
 
i tried to add a blank database in the package but ..........i couldnt find the prob..

GeneralStatementmemberxs314 Apr '09 - 21:58 
hi there,
the post was really informative.
I would also like to add that the Statement used id of java.sql.Statement.
There are also 2 more types of statement that are available.
1. Prepared Statement.
 

String username="xyz"; //Username to be inserted into the table usertable
String pwd="123";      //password 
String cmt="blah blah..";    //comments for the user

PreparedStatement ps = con.prepareStatement("INSERT INTO usertable(userid,password,comments) VALUES(?,?,?)");                  // create an object of the prepared statement<
ps.setString(1,username);   //maps what value to insert in the first column - here username
ps.setString(2,pwd);        //maps what value to insert in the secend column - here the password
ps.setString(3,cmt);
ps.execute();
 
ps.setString(column index,string) - used ti map string type data
ps.setInt(column index,int) - used to map int type data
...
 
2. Callable statements
 
Callable statements are used to invoke stored procedures stored in the database. The use of stored procedures and Callable statement enhance the sclability and maintainability of the code. Refer to the Java documentation for the CallableStatement.
 
Thumbs Up | :thumbsup:
GeneralRe: Statementmemberarnavguddu16 Apr '09 - 8:36 
Thank you for your comment and add...
 
Arnav
( http://pendorasoft.byethost15.com/ )

GeneralThe Code in the above article was updated as s.close() and conn.close would have never been reached if an exception was thrown before that code part is reached....memberarnavguddu14 Apr '09 - 7:18 
/* 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)
{
Connection conn = null;
Statement s = null;
 
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=myDB.mdb;";
conn = DriverManager.getConnection(database, "", "");
s = conn.createStatement();

// create a table
String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
String createTable = "CREATE TABLE " + tableName + " (id Integer, name Text(32))";
s.execute(createTable);

// enter value into table
for(int i=0; i<25; i++)
{
String addRow = "INSERT INTO " + tableName + " VALUES ( " + String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + String.valueOf(Math.random()) + "')";
s.execute(addRow);
}

// Fetch table
String selTable = "SELECT * FROM " + tableName;
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!=null) && (rs.next()))
{
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}

// drop the table
String dropTable = "DROP TABLE " + tableName;
s.execute(dropTable);
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
// So we are done... Lets close and cleanup!!!
try
{
if(s != null)
s.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}

try
{
if(conn != null)
conn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}

}
}
}
 
Arnav

Generaljava driversmembermaha_i_haba14 Apr '09 - 2:20 
Morning to all,
 
Thanks for this one article, this come when I need Wink | ;-)
 
But one question, please: Is this driver in each JVM? Or it is supposed to be add?
 
Thanks to answer.
 
Martin
GeneralRe: java driversmemberarnavguddu14 Apr '09 - 7:20 
yup.... drivers are preinstalled in JVM. But 3rd party drivers can also be added and it is even possible to write your own drivers too...
 
Arnav

GeneralMy vote of 1memberrmarkram7 Apr '09 - 2:09 
This is nothing new and have been done over and over.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 6 Apr 2009
Article Copyright 2009 by arnavguddu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid