I am trying to use an external mysql database in my java application, but I keep getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
when the application tries to make a connection.
This is the code I use to open the connection.
What is causing this?
// Post: A connection is opened if the current connection is not valid
private static boolean open() throws SQLException {
// If connection is still valid, return without doing anything
try {
if (connection != null && connection.isValid(1)) {
return true;
}
}
catch (SQLException e1) {
close();
}
// Start connecting
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://mysql.starredout.com/" + database;
String user = "starredout";
String password = "starredout";
try {
Class.forName(driver).newInstance();
}
catch (Exception e) {
e.printStackTrace();
return false;
}
connection = DriverManager.getConnection(url,user,password);
return true;
}
// Post: If a connection was open, it is closed
private static void close() {
try {
if (connection == null || connection.isClosed())
return;
connection.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
That error means that it couldnt find the class you tried to make it run.
This is probably caused because you forgot to link the driver library to your build path?
The library is probably stored in a .jar file, so you have to mention that jar in your classpath.
In case you use eclipse just right click your project ==> Build path ==> configure build path, then click the Libraries tab, and click Add JARs… and select the jar you wish to include in the classpath
In other IDE’s it should be a similar process