Solved

Java connection to MS ACCESS.

Posted on 2003-11-05
3
2,369 Views
Last Modified: 2010-08-05
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;
      }
}
0
Comment
Question by:JK2429
3 Comments
 
LVL 15

Expert Comment

by:Javatm
ID: 9691650
Here is a sample of how you can connect through ms access :

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20773695.html
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20492543.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
0
 
LVL 92

Expert Comment

by:objects
ID: 9691651
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

0
 
LVL 16

Accepted Solution

by:
gnoon earned 75 total points
ID: 9692099
Your main method:

>public static void main(String args[])
>{
>     System.out.println("Starting Foo...");
>      Foo f; // <-- it's not get some instance of Foo, so the constructor is not called
>}

should look like this:

public static void main(String args[])
{
      System.out.println("Starting Foo...");
      Foo f = new Foo();
}

and do follow the experts's suggestions above.

I suggest that you should use the command
      Connection con = DriverManager.getConnection(dsn); // connection with no username and password
if your DSN is not have the Default Authorization. I don not know why but I try to use username="" and
password="" in my project, it's not work.

-gnoon-
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now