Java with MS Access database

May 27, 2007

MS Access database is available with all MS (Microsoft) office. Its a very simple database to use for small business or home maintenance. Here the demonstration for using MS Access with java. Open MS Access and create a new data with name nsu and save that. Then use the following java code in the same directory, compile and run. It will create a new table named student, insert data and retrieve data from the table.

import java.sql.*;

public class Testac
{
public static void main(String[] args){
try {

System.out.println(“Begining conn”);

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

String accessFileName = “nsu”;

String connURL=”jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=”+accessFileName+”.mdb;PWD=”;

Connection con = DriverManager.getConnection(connURL, “”,”");

Statement stmt = con.createStatement();

System.out.println(“Conn done succesfully”);

stmt.execute(“create table student ( Name string, ID integer )”); // create a student

stmt.execute(“insert into student values(‘Md. SHAHJALAL’, ’02223540′)”); // insert data into student

stmt.execute(“select * from student”); // execute query in table student

ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query

if (rs != null)
while ( rs.next() ){

System.out.println(“Name: ” + rs.getString(“Name”) + ” ID: “+rs.getString(“ID”));
}

stmt.close();
con.close();
}
catch (Exception err) {
System.out.println(“ERROR: ” + err);
}
}
}

By: Md. Shahjalal


Follow

Get every new post delivered to your Inbox.