Solved

Java connection to MS ACCESS.

Posted on 2003-11-05
3
2,386 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Why does the Android Studio logcat show this error when the user presses the button? 2 46
MySQL  on Tomcat 8 48
use lov values 2 52
Problem to Alipay 10 25
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

825 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