Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Connecting MySQL & Java

807599Mar 17 2007 — edited Mar 18 2007
Hi,

I have a database in MySQL called employee. I'm trying to learn how to connect to this database through java.

In MySQL logged in as root, I typed this command:

GRANT ALL PRIVILEGES ON *.* TO 'username'@'localhost'
* IDENTIFIED BY 'password' WITH GRANT OPTION;

I have a class called Connect which looks like:
   import java.sql.*;

   public class Connect
   {
       public static void main (String[] args)
       {
           Connection conn = null;

           try
           {
               String userName = "username";
               String password = "password";
               String url = "jdbc:mysql://localhost";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               System.err.println ("Cannot connect to database server");
           }
           finally
           {
               if (conn != null)
               {
                   try
                   {
                       conn.close ();
                       System.out.println ("Database connection terminated");
                   }
                   catch (Exception e) { /* ignore close errors */ }
               }
           }
       }
   }
I downloaded
mysql-connector-java-3.1.14-bin.jar
and placed it in
C:\Program Files\Java\jdk1.5.0_04\jre\lib\ext
. I also placed it in my java projects folder.

I get the error: Cannot connect to database server

I read something about needing to set CLASSPATH. But they didn't say how to set CLASSPATH.

I don't even know what CLASSPATH is/means, how can I set
mysql-connector-java-3.1.14-bin.jar
to it?

Thanks!
shlumph.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 15 2007
Added on Mar 17 2007
9 comments
166 views