Sample Java Program to test microsoft access odbc connection

Copy file to shared folder java

Below is the sample java program which tests the connection to MS ACCESS database.
Here we do create a table, insert some data to the table and select the same data back as output to test the connectivity.We drop the dummy table post testing the connection.

 
import java.sql.*;
public class msaccess
{
public static void main(String[] args) 
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
/* the next 3 lines are Step 2 method 2 from above - you could use the direct
access method (Step 2 method 1) istead if you wanted */
String dataSourceName = "msa";

String dbURL = "jdbc:odbc:" + dataSourceName;
Connection con = DriverManager.getConnection(dbURL, "","");
// try and create a java.sql.Statement so we can run queries
Statement s = con.createStatement();
s.execute("create table TEST12345 ( column_name integer )"); // create a table
s.execute("insert into TEST12345 values(1)"); // insert some data into the table
s.execute("select column_name from TEST12345"); // select the data from the table
ResultSet rs = s.getResultSet(); // get any ResultSet that came from our query
if (rs != null) // if rs == null, then there is no ResultSet to view

while ( rs.next() ) // this will step through our data row-by-row< {

/* the next line will get the first column in our current row's ResultSet
as a String ( getString( columnNumber) ) and output it to the screen */
System.out.println("Data from column_name: " + rs.getString(1) );
}
 s.execute("drop table TEST12345");
s.close(); // close the Statement to let the database know we're done with it
con.close(); // close the Connection to let the database know we're done with it
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}

 

This program is not developed by me, rather I had it with me for long time to test basic connection to MS Access, so thought of posting.

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.