Hi all,

Im fairly new to java. Im wanting to connect to mysql but the following is thrown

Exception: com.mysql.jdbc.Driver

have i missed something?

here is the code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySql {

  public static void main(String args[]) throws Exception
  {
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con = DriverManager.getConnection("jdbc:mysql:///test",
        "username", "password");

      if(!con.isClosed())
        System.out.println("Successfully connected to " +
          "MySQL server using TCP/IP...");

    } catch(Exception e) {
      System.err.println("Exception: " + e.getMessage());
    } finally {
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {}
    }
  }
}

Recommended Answers

All 21 Replies

on another note, i tried something a little different. At least this one says "cant connect to database"

import java.sql.*;

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

           try
           {
               String userName = "un";
               String password = "pw";
               String url = "jdbc:mysql://127.0.0.1:3306/test/";
               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 */ }
               }
           }
       }
   }

Solution Is here
Hi ...... I had also faced the

Exception: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

While connecting Java application to the mysql.
On both platform windows and linux

I m done with its solution and writing the steps i followed ... Hope it will help

1 . The java code for connectivity

<code>

import java.sql.*;

public class Jdbc11 {
public static void main(String args[]){

try {
Statement stmt;
Class.forName("com.mysql.jdbc.Driver");
String url ="jdbc:mysql://localhost:3306/mysql";
Connection con = DriverManager.getConnection(url,"root", "");
stmt = con.createStatement();
stmt.executeUpdate("CREATE DATABASE payroll1");
stmt.executeUpdate(
"GRANT SELECT,INSERT,UPDATE,DELETE," +
"CREATE,DROP " +
"ON JunkDB.* TO 'root'@'localhost' " +
"IDENTIFIED BY '';");
con.close();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end main
}//end class Jdbc11

</code>

This code on execution will create a database named payroll1......

2.
Mysql is installed by default on port 3306
if you will simply install the mysql and run the above code
you will get the

Exception: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

3
Here is the solution for this for windows


Simply put a file Named
" mysql-connector-java-3.0.17-ga-bin.jar "
(You can get this file easily downloadable on Internet , Search by
its name)
on the following location ... i m giving the location where i put it

" C:\Program Files\Java\jdk1.6.0_14\jre\lib\ext "

Simply paste the " mysql-connector-java-3.0.17-ga-bin.jar "
file over the above location relative to your machine....

After this execute the code it will gonna work fine....
Our editors will seek connector on the above location
but for deployed application read below....

Secondly when you will deploy your connectivity code into an
application , then u will have to save the connector
" mysql-connector-java-3.0.17-ga-bin.jar "
on the following location
i m giving the location where i put it
" C:\Program Files\Java\jre6\lib\ext "
deployed application will seek connector on this location...

it will gonna work fine after this....create stattement object and
execute as much query as you want

4 Here is the solution <b>for Linux</b>

simply put the connector
" mysql-connector-java-3.0.17-ga-bin.jar "

on the following location...i m giving the location where i put it
" /usr/rohitsharmahome/lib/jvm/default-java/jre/lib/ext "

i need to restart the system to verify whether i wrote the right location for linux...Because i m working on windows right now...so forgive and work yourself to find the exact location ,,but trust me i think i wrote the right location....try your self....

Putting anything in default Java installation directory is bad idea. If you creating just simple application you can keep JAR file in same directory as your source code for easy compiling. However while working on something larger you should set up special folder for any external resources ("lib") and either manage linking to your project through IDE or with Ant or Maven configuration files (which IDE basically does for you on background).

Your mistake as already pointed was in use of incorrect connection string that should be

//Pseudo code
jdbc:mysql://<HOST>:<PORT>/<DB>
//Example code
jdbc:mysql://localhost/danijsptutorial
//or with port number if database uses other then default port
jdbc:mysql://localhost:3306/danijsptutorial

Examples of connection string for other databases can be found here

Hi All,

Thanks for your help all.

Im convinced that there is nothing wrong with the code. Both give exceptions, which i have defined. One is Exception: the driver, and the other is cannot connect.

With this in mind, i think i have not defined a class path, which on its own it a pain.

java -cp /my/own/classes/jar.jar myApp

i jave tried the above in the mac shell.

aaaaaaaaaaaaaaaaaaah

Please provide connection strings as you tried including exceptions you received.

hi,

this is the java

String userName = "root";
               String password = "root";
               String url = "jdbc:mysql://localhost:8888/test/";
               Class.forName ("com.mysql.jdbc.Driver").newInstance ();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");

The jar file is mysql-connector-java-3.0.17-ga-bin.jar

Any specific reason you used 8888 for port number? MySQL is by default installed on 3306.

i have that in as ive been trying mamp and mysql stand alone

Ive made sure ive not had both on at the same time, but mamp uses 8888 and the other, as you say is 3306

Dunno why people insists on installing MAMP/WAMP/XAMP when they are about to do Java development and they do not need PHP and Apache.
Now you need to figure out on which port is your instance of MySQL running and each time you try to work with database you will need to have your Apache server running.
Solution delete MAMP and install MySQL only.

Hi,

Thats the issue, i do use php and apache, which is a whole new kettle of fish.

However, i do now have a live server, so i think ill take your advice.

Thanks for your help

hi all,

ive installed xp on vmware fusion, installed all of the updates, jdk, netbeans and mysql server. The user is set up, but exactly the same exception.

What on earth am i not doing here?

how do i install this bloody driver?

Ahh hell, I forgot about connector and it dependency on classpath.
To beat this either set classpath or use following in command prompt/line

//compile
javac MysqlTest.java -cp mysql-connector-java-5.0.8-bin.jar
//execution
java MysqlTest -cp mysql-connector-java-5.0.8-bin.jar

Change the name of the application and driver name in regards what you have.

import java.sql.*;

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

           try
           {
               String userName = "root"; //change it to your username
               String password = ""; //change it to your password
               String url = "jdbc:mysql://localhost:3306/test";
               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 */ }
               }
           }
       }
   }

Hi,

firstly i love you,

secondly, is there a way i can get this to work in netbeans?

or is it best to avoid netbeans for running

In your project create create new package "lib". Right click on the project and select Properties. In the pop-up window, in CATEGORIES (left side listing) select Libraries & Resources >>on the right press Add JAR/Folder and navigate to place where is the driver or any other library you wish to add >> highlight file/s you want to include and press OK.


However if the projects are just learning (no-production) you may want to just create a directory somewhere on the disk that you can re-use for attaching Connector/J. In this scenario just skip the section for package creation and go directly for adding resources.

commented: peter is a good programmer. I like suggetions posted by him. +0

Hi javanator, your given solution solved my problem, you got the correct solutio for ClassNotFound Exception in the given scenario to connect Java with WAMP MySQL.
Thank you.:)

Hi javanator, your given solution solved my problem, you got the correct solutio for ClassNotFound Exception in the given scenario to connect Java with WAMP MySQL.
Thank you.:)

If you installed WAMP just because of that, then shame... Proper source allocation/linking is all what is need it.

Its in requirement of my project to work with WAMP. I am a sophisticated programmer and don't do shame things. Still, Thank u!

Who came with that idea is idiot. Only reason to use Apache server would to have as top container for Java server/container and even then I would do it as separate installation not with preconfigured package for PHP (which WAMP/XAMP essentially is)

Has PHP as smart File System processing Like Java?
And also Java has smart regular expression compilation and comparison(Package regex) technique to pick specific contents from a jumble crumbled file to store them in DataBase. PHP just to represent it over a WEB UI with some analysis.

Yes peter, you are absolutely right, its not good practice to alter default editors folders. So, i also undo the option to save jar file in C:\Program Files\Java\jdk1.6.0_14\jre\lib\ext to enable DRIVER in my application. Now the jar file in library folder of my project's folder. I didn't see the all threads thats y i adopt only the first one solution but now its clear to me.

Well for some back end processing i am using JAVA( NetBeans ) and PHP to create WEB UI in my project.

Thanks bddy for correcting! :cool:


Putting anything in default Java installation directory is bad idea. If you creating just simple application you can keep JAR file in same directory as your source code for easy compiling. However while working on something larger you should set up special folder for any external resources ("lib") and either manage linking to your project through IDE or with Ant or Maven configuration files (which IDE basically does for you on background).

Your mistake as already pointed was in use of incorrect connection string that should be

//Pseudo code
jdbc:mysql://<HOST>:<PORT>/<DB>
//Example code
jdbc:mysql://localhost/danijsptutorial
//or with port number if database uses other then default port
jdbc:mysql://localhost:3306/danijsptutorial

Examples of connection string for other databases can be found here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.