Reputation: 2513
I am trying to set up a connection with a MySQL database with Java using JDBC.
But when I try to do this, I get some errors. I'm sure the problem is not because of a wrong MySQL server setting, because I tried to connect with MySQL Workbench, and this works.
I use this Java code to set up de JDBC connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnection {
public static SQLConnection instance = new SQLConnection();
public static String URL = "jdbc:mysql://localhost:3306/canbusdata";
public static String USER= "root";
public static String PSW = "root";
public SQLConnection()
{
}
public static Connection getConnection() {
System.out.println("-------- MySQL JDBC Connection ------------\n");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(URL,USER,PSW);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console: \n");
e.printStackTrace();
}
return connection;
}
}
But I get this error:
-------- MySQL JDBC Connection ------------
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Where is your MySQL JDBC Driver?
MySQL JDBC Driver Registered!
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
Connection Failed! Check output console:
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at SQLConnection.getConnection(SQLConnection.java:21)
at Start.ProcessData(Start.java:109)
at Start.main(Start.java:21)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/canbusdata
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at SQLConnection.getConnection(SQLConnection.java:31)
at Start.ProcessData(Start.java:109)
at Start.main(Start.java:21)
Exception in thread "main" java.lang.NullPointerException
at Start.ProcessData(Start.java:110)
at Start.main(Start.java:21)
Java Result: 1
Upvotes: 0
Views: 1838
Reputation: 444
Download this jar and include in Built path it will work
mysql-connector-java-5.1.18-bin.jar
Hope this helps.
Upvotes: 1
Reputation: 85789
Looks like you haven't configured your JDBC driver in your project. Make sure to add it to the classpath before running it (through command line or IDE based).
Upvotes: 2