Link to home
Start Free TrialLog in
Avatar of JK2429
JK2429

asked on

Java connection to MS ACCESS.

I have the follwing code.  When I compile it, it returns no errors or warnings.  But when I execute it, it doesn't even go in the program for some reason.  Not sure whats wrong with it.  My ODBC:JDBC is configured in my control panel as well.  Any assistance with this would be greatly appreciated.

//In XP (Assuming you have saved the MS ACCESS to your hard drive.
//1.  go to Control Panel
//2.  go to Administrative Tools
//3.  go to Data Sources (ODBC)
//4.  click on Add if MS ACCESS Database driver not present. and follow from there then 5.
//5.  If MS ACCESS Database driver is present, go on to 6.
//6.  Click on System DSN tab.
//7.  Click on Add button
//8.  Click on Driver do Miccrosoft Access (*mdb)
//9.  Type in data source name and description.  (I used db1).
//10. Click on Select button and go to the directory of where the Access database was saved.
//11. System Database radiobutton should be none.
//12. Click OK and OK!

package myprojects.foo;

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.util.Vector;

//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
class Foo
{
            // ODBC data source name
            String dsn = "jdbc:odbc:db1";
            String user = "admin";
            String password = "abc";

      public Foo()
      {
            try
            {
                  // Connect to the database
                  Connection con = DriverManager.getConnection(dsn, user, password);
                  System.out.println("Connected to DB");
            }
            catch(SQLException sqle)
            {
                  sqle.getErrorCode();
                  System.out.println("Couldn't connect to database!");
            }

            //data source name = db1
            //description = db1
            //select path = C:\Stuff\db1\rtg.mdb

            try
            {
                  Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
            }
                  
            catch(ClassNotFoundException ee)
        {
              ee.printStackTrace();
        }    
            
          Statement stmt;       // SQL statement object
          String query;         // SQL select string
          ResultSet rs;               // SQL query results
          boolean more;            // more rows found
          String v1, v2, v3;      // temporary storage results

          Vector results = new Vector(10);

          query = "SELECT Email, LName, FName, Password" + "FROM Customer";


             try
        {
              Connection con = DriverManager.getConnection(dsn, user, password);
                   stmt = con.createStatement();
                   
                   rs = stmt.executeQuery(query);
   
                   // Check to see if any rows were read
                   more = rs.next();
              if (!more)
              {
                    System.out.println("No rows found.");
                  return;
                  }

              // Loop through the rows retrieved from the query
              while (more)
              {
                    v1 = "Email Address: " + rs.getInt("Email");
                v2 = "Name: " + rs.getString("FName") + " " + rs.getString("LName");
                v3 = "Password: " + rs.getString("Password");

                  System.out.println(v1);
                  System.out.println(v2);
                  System.out.println(v3);
                  System.out.println("");    

                results.addElement( v1 + "\n" + v2 + "\n" + v3 + "\n");
                  more = rs.next();
            }

                   rs.close();
              stmt.close();
        }
        catch (SQLException e)
        {
              System.out.println("" + results.size() + " results where found.");
        }
    }

      public static void main(String args[])
      {
            System.out.println("Starting Foo...");
            Foo f;
      }
}
Avatar of Javatm
Javatm
Flag of Singapore image

Here is a sample of how you can connect through ms access :

https://www.experts-exchange.com/questions/20773695/Connect-to-MS-Access-database-from-java-code.html
https://www.experts-exchange.com/questions/20492543/JDBC-Problem-in-adding-a-record-to-Access-Database.html

Usefull Link :

http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q=Java+%26+MS+Access

Study Guide :

http://java.sun.com/docs/books/tutorial/jdbc/
http://java.sun.com/products/jdbc/
http://www-db.stanford.edu/~ullman/fcdb/oracle/or-jdbc.html

Simple Sample :

import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Database {

public static void main(String args[]) {

  Connection connect;
  String url;

  try {

  // change the Yourdatabase with your database
  url = "jdbc:odbc:Yourdatabase";

  // You could use the direct or indirect way
  Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
  connect = DriverManager.getConnection( url );

   // If you decided to use this then remove some 2 codes above
   // Specify your database here
  // connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)};DBQ="+"dbLocation","username","PWD");

  JOptionPane.showMessageDialog(null,"Connection Successful !",
  "Database . . .",JOptionPane.PLAIN_MESSAGE);    
  }
  catch ( ClassNotFoundException cnfex ) {
  cnfex.printStackTrace();
  }
  catch ( SQLException sqlex ) {
  sqlex.printStackTrace();
  }
  catch ( Exception ex ) {
  ex.printStackTrace();
  }

}
}

Here are my own personal help :

1.) 1st thing you need to do is to create 1st a database on access.
2.) connect your database with your .java using jdbc-odbc bridge.

     You can do it in to ways :
     a.) Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
          connect = DriverManager.getConnection( url );
          After that go to control panel and set-up the database under data sources (odbc)
          If your in windows xp it under administrative tools under control panel.

     b.) Or you can use this for direct connection :
          connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver(*.mdb)};
          DBQ="+"dbLocation","username","PWD");

3.) You can now compile and run.
4.) Sample above is just a connection sample for your database.


Hope this helps . . .
JAVATM
Avatar of Mick Barry
load the driver class before u get the connection:

          try
          {
               Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
          }
               
          catch(ClassNotFoundException ee)
        {
             ee.printStackTrace();
        }    

          try
          {
               // Connect to the database
               Connection con = DriverManager.getConnection(dsn, user, password);
               System.out.println("Connected to DB");
          }
          catch(SQLException sqle)
          {
               sqle.getErrorCode();
               System.out.println("Couldn't connect to database!");
          }

          //data source name = db1
          //description = db1
          //select path = C:\Stuff\db1\rtg.mdb

ASKER CERTIFIED SOLUTION
Avatar of gnoon
gnoon
Flag of Thailand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial