Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2006

Tip: Looking for answers? Try searching our database.

Connect to access

Thread view: 
morc - 24 May 2006 19:11 GMT
Hi,
i haven't been doing database related programming for a large period of
time.
I have forgotten how to connect to a databse.
if someone could please do me the favour of giving me an example of
how to connect to access db and run a query.

thanks in adavnce
-morc
Rhino - 24 May 2006 19:29 GMT
> Hi,
> i haven't been doing database related programming for a large period of
> time.
> I have forgotten how to connect to a databse.
> if someone could please do me the favour of giving me an example of
> how to connect to access db and run a query.

Here are some fragments that should answer your questions; your code simply
needs to invoke the three methods at the appropriate time. Naturally, the
sequence should be that you load the JDBC driver first, then get a
connection to the database, then query or update the database. You'll also
want to define some variables as follows:

   final String CLASS_NAME = getClass().getName();
   Connection conn01 = null;
   static final String DEMO_TABLE = "RHINO.PERSONNEL";

public void loadDriver() {

       String METHOD_NAME = "loadDriver()";

       /* Initialize the variable that contains the name of the JDBC
driver. */
       String jdbcDriverName = "com.ibm.db2.jcc.DB2Driver";

       /* Load the JDBC driver. */
       try {
           Class.forName(jdbcDriverName);
       } catch (ClassNotFoundException excp) {
           System.err.println(CLASS_NAME + "." + METHOD_NAME + " -
Encountered ClassNotFoundException while attempting to load JDBC driver " +
jdbcDriverName + ". Error: " + excp);
           excp.printStackTrace();
           System.exit(16);
       }
   }

   public void connectToDatabase() {

       String METHOD_NAME = "connectToDatabase()";

       /* Initialize the variables used to get the connection. */
       String databaseName = "sample";
       String url = "jdbc:db2:" + databaseName;
       String loginName = "admin";
       String password = "adminpw";

       /* Connect to the database. */
       try {
           conn01 = DriverManager.getConnection(url, loginName, password);
       } catch (SQLException sql_excp) {
           System.err.println(CLASS_NAME + "." + METHOD_NAME
                   + " - Encountered SQLException on connect to URL " + url
+ ". Error: "
                   + sql_excp);
           sql_excp.printStackTrace();
           System.exit(16);
       }

       /* Set autocommit off. */
       try {
           conn01.setAutoCommit(false);
           System.out.println("Turn off autocommit...");
       } catch (SQLException sql_excp) {
           System.err.println(CLASS_NAME + "." + METHOD_NAME
                   + " - Encountered SQLException on attempt to turn
autocommit off. Error: "
                   + sql_excp);
           sql_excp.printStackTrace();
           System.exit(16);
       }
   }

   public void queryTable() {

       String METHOD_NAME = "queryTable()";

       System.out.println("Current D21 rows in the table: ");
       String queryTableSQL = "select lastname, workdept, salary, hiredate
from "
               + DEMO_TABLE + " where workdept = 'D21' ";

       /*
        * Query the demonstration table to get information about certain
        * employees.
        */
       Statement queryTableStmt = null;
       ResultSet rs01 = null;
       try {
           queryTableStmt = conn01.createStatement();
           rs01 = queryTableStmt.executeQuery(queryTableSQL);
       } catch (SQLException excp) {
           System.err.println(CLASS_NAME + "." + METHOD_NAME
                   + " - Encountered SQLException while trying to get
information from "
                   + DEMO_TABLE + " table. Error: " + excp);
           excp.printStackTrace();
           System.exit(16);
       }

       /* Initialize the host variables used for handling the result set.
*/
       String lastname = null;
       String workdept = null;
       BigDecimal salary = null;
       java.sql.Date hiredate;

       /*
        * Print each line of the result set. The salary, which is a double,
is
        * converted to a BigDecimal and then copied to another BigDecimal
that
        * has exactly 2 decimal places.
        */
       try {
           while (rs01.next()) {
               lastname = rs01.getString(1);
               workdept = rs01.getString(2);
               salary = rs01.getBigDecimal(3);
               hiredate = rs01.getDate(4);
               System.out.println(lastname + "  " + workdept + "  " +
salary.toString() + "  "
                   + hiredate.toString());
           }
       } catch (SQLException sql_excp) {
           System.err.println(CLASS_NAME + "." + METHOD_NAME
                   + " - Encountered SQLException while reading " +
demoTable
                   + " table. Error: " + sql_excp);
           sql_excp.printStackTrace();
           System.exit(16);
       }

       /* Close the result set, dispose of the statement, and commit. */
       try {
           rs01.close();
           queryTableStmt.close();
           conn01.commit();
       } catch (SQLException sql_excp) {
           System.err.println(CLASS_NAME + "." + METHOD_NAME
                   + " - Encountered SQLException while closing " +
demoTable
                   + " result set, closing statement, or committing. Error:
" + sql_excp);
           sql_excp.printStackTrace();
           System.exit(16);
       }
   }

--
Rhino
morc - 24 May 2006 19:44 GMT
thanks alot this is what i was looking for
stupid question:
how can i find the info on my current jdbc driver? and if i don't have
one where do i get it and how to installs it.

Im not familiar with doing this so all help is appreciated.
-morc
morc - 24 May 2006 20:47 GMT
public void connect(){

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

        String databaseName = "invent";
       String url = "jdbc:odbc:" + databaseName;
       String loginName = "Admin";
       String password = "lace";

       try {
            conn01 = DriverManager.getConnection(url, loginName, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

this is the code i used.
this is the error i get:
java.lang.ClassNotFoundException: sun.jdbc.odbc.JbdcOdbcDriver
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at allm.test.DBaccess.connect(DBaccess.java:18)
    at allm.test.test.main(test.java:17)
java.sql.SQLException: No suitable driver
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at allm.test.DBaccess.connect(DBaccess.java:29)
    at allm.test.test.main(test.java:17)

can somebody please pooint me in the right direction.
do i need to configure somethign in access? is there any thing i have
to do in the ODBC configurations?
Rhino - 24 May 2006 21:57 GMT
> thanks alot this is what i was looking for
> stupid question:
[quoted text clipped - 3 lines]
> Im not familiar with doing this so all help is appreciated.
> -morc

According to the post which shows your error message, you appear to be using
the Sun JDBC/ODBC Driver. That driver can be found in the rt.jar file. If
you have a JDK installed on your machine, rt.jar can be found in the jre\lib
folder. If you have a JRE installed on your machine, you should find it in
the lib folder. As long as you have the JDK or the JRE in your PATH, your
Java program should be able to find it and use it.

I'm going to do a few tests just to verify this on my machine, then I'll
post back. This is just a quick note to let you know that I'm working on the
problem.

--
Rhino
Rhino - 24 May 2006 22:16 GMT
>> thanks alot this is what i was looking for
>> stupid question:
[quoted text clipped - 14 lines]
> post back. This is just a quick note to let you know that I'm working on
> the problem.

Sorry, I thought that should work but when I tried it, I got the same
problem you did: ClassNotFoundException when I tried to load the driver. I
had rt.jar in the Build Path (the Eclipse equivalent of Classpath) and even
moved it to the top but it made no difference. For some reason, it's not
seeing the driver and I can't think of anything else to try offhand.

Why don't you try going to the comp.lang.java.databases newsgroup? Try a
Google Groups search on Access or the driver name first since someone must
have had and solved this problem before. If that doesn't work, try a new
post and explain your problem.

Post back here when you have the answer; now that I've spent time on your
problem, I'm interested in hearing the solution ;-)

--
Rhino
TechBookReport - 25 May 2006 10:22 GMT
>>> thanks alot this is what i was looking for
>>> stupid question:
[quoted text clipped - 31 lines]
> --
> Rhino

Don't forget that if you're using ODBC you need to set up a DSN that
maps the dbname to a real database.

Signature

TechBookReport Java http://www.techbookreport.com/JavaIndex.html

Rhino - 25 May 2006 13:47 GMT
>>>> thanks alot this is what i was looking for
>>>> stupid question:
[quoted text clipped - 33 lines]
> Don't forget that if you're using ODBC you need to set up a DSN that maps
> the dbname to a real database.

Yes, I expected to have to do that. But it doesn't explain why we get the
ClassNotFoundException while trying to load the driver.

--
Rhino
morc - 25 May 2006 14:54 GMT
I found the error it was a simple spelling mistgake
thx for ur help
morc - 25 May 2006 15:38 GMT
I found the error it was a simple spelling mistgake
thx for ur help
IchBin - 24 May 2006 23:32 GMT
> Hi,
> i haven't been doing database related programming for a large period of
[quoted text clipped - 5 lines]
> thanks in adavnce
> -morc

There was just that same discussion, in the last hour, funny enough it
is in the DATABASE NG, alt.comp.lang.java.databases

Look at
http://www.javaworld.com/javaworld/javaqa/2000-09/03-qa-0922-access.html

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)
IchBin - 24 May 2006 23:37 GMT
>> Hi,
>> i haven't been doing database related programming for a large period of
[quoted text clipped - 11 lines]
> Look at
> http://www.javaworld.com/javaworld/javaqa/2000-09/03-qa-0922-access.html

I Should have read this thread first before I posted... This was
answered in alt.comp.lang.java.databases. The OP has failed to mention
he is working two NG's.

He had miss spelled the the driver name.

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.