Saturday, May 5, 2012

DSN-Less MSAccess connection

public Connection getConnection() throws Exception {  
 try{
                // Load the driver
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        String filename = "C:/Users/Dipayan/Desktop/dic.mdb";
    String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
    database+=filename.trim() + ";DriverID=22;READONLY=true}";
    Connection conn=DriverManager.getConnection(database,"","");    
                        System.out.println("Connected to the dictionary");  
                     // Create a Statement
                        Statement stmt = conn.createStatement();
                        System.out.println("Statement Created"); 
                        // Create a query String
                        
                        ResultSet rs = stmt.executeQuery("SELECT meaning FROM dictionary where word='"+str+"'");
                        System.out.println("Query Executed"); 
                        while(rs.next())
                        {
                          text = rs.getString(1).toString();
                         // System.out.print(t);
                         
                        } 
                              
                        stmt.close();
                        conn.close();
                        System.out.println("Disconnected from database");
                }
                catch(SQLException e) {
                            e.printStackTrace();
                } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}