Solved

Java connection to MS ACCESS.

Posted on 2003-11-05
3
2,404 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn different types of Android Layout and some basics of an Android App.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video teaches viewers about errors in exception handling.

707 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