25 Sept 2012

jdbc odbc connection for ms access in java

/* jdbc odbc connection for ms access in java code, jdbc-odbc connection in java with ms-access*/ 
import static java.lang.System.*;
import java.sql.*;

public class DBDemo
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String sourceURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=UserDB.mdb;";
            Connection userDB = DriverManager.getConnection(sourceURL, "admin", "");
            Statement myStatement = userDB.createStatement();
            String writeString = "INSERT INTO Users(Firstname,Surname,Id)                     
            VALUES('Fred','Bloggs','bf01')";
            myStatement.executeUpdate(writeString);

            ResultSet results = myStatement.executeQuery("SELECT Firstname, Surname, Id FROM Users 
            ORDER BY Id");

            while (results.next())
            {
                out.print(results.getString(1) + " ");
                out.print(results.getString(2) + " ");
                out.println(results.getString(3));
            }
            results.close();
        }
        //The following exceptions MUST be caught
        catch(ClassNotFoundException cnfe)
        {
            out.println(cnfe);
        }
        catch(SQLException sqle)
        {
            out.println(sqle);
        }
    }
}

0 comments:

Post a Comment