-1

Here is the code that i am using to connect to MysSQL database using java.....

I am getting a runtime error...

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

public class Java2MySql 
{
    public static void main(String[] args) 
    {
          String url = "jdbc:mysql://localhost:3306/";
          String dbName = "java_test";

          String driver = "com.mysql.jdbc.Driver";
          String userName = "root"; 
          String password = "plsdonthack";

        try 
        {
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url+dbName,userName,password);

            conn.close();

        }
        catch (Exception e) 
        {
             e.printStackTrace();
        }
    }
}

I am running it like this : java -cp "$HOME/OOPS-Files/Code/learn/Driver/mysql-connector-java-5.1.34-bin.jar" Java2MySql

I have the .jar file there.

Here is the Error Message That i get when i run it.

I have physically gone and checked the folder com/mysql/jdbc and have found the file called Driver.java there....

Error: Could not find or load main class Java2MySql

PRP
  • 1,469
  • 2
  • 16
  • 32

2 Answers2

1

The MySQL connector library Jar file needs to be in your classpath.

See : http://dev.mysql.com/downloads/connector/j/

Information how to set the classpath can be found in this posting Setting multiple jars in java classpath

In your case however it looks like you forgot to add your own code to the classpath. As you set the classpath with

java -cp "$HOME/OOPS-Files/Code/learn/Driver/mysql-connector-java-5.1.34-bin.jar" Java2MySql

your own code is not on the classpath anymore. So you need to include "." in the classpath (assuming that you run the java command from the same directory where your compiled classes are sitting.

java -cp "$HOME/OOPS-Files/Code/learn/Driver/mysql-connector-java-5.1.34-bin.jar:." Java2MySql
Community
  • 1
  • 1
Matthias Steinbauer
  • 1,641
  • 9
  • 23
0

Place your MySQL connector jar in the lib folder, which you can find under, WebContent -> WEB-INF folder. It should work.

xtras
  • 116
  • 4
  • 15