Reputation: 762
I am attempting to connect to a mysql database, with a connection url of:
jdbc:mysql://127.0.0.1:3306/test
I have downloaded the coorect Mysql driver to connect with the database, and have tried a multitude of approaches to set the driver, with each not working. So far I have tried placing the JAR file in the following places (and changing the PATH environment variable accordingly)
JRE/LIB/
JDK/LIB/
JRE/LIB/mysql-connector-java-5.1.21
JDK/LIB/mysql-connector-java-5.1.21
The path for the JAR file has been its location + mysql-connector-java-5.1.21-bin.jar
Over the last 4+ hours I have read multiple questions and solutions on StackOverflow, as well as online tutorials about this issue, and none have solved the problem.
I have been using the following code to attempt a connection
import java.sql.*;
import java.util.Date;
public class DatabaseHelper{
private Connection conn = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private String url = null;
public DatabaseHelper(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test");
System.out.println("Driver Loaded!");
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
Stacktrace
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at DatabaseHelper.<init>(DatabaseHelper.java:28)
at DatabaseTest.<init>(DatabaseTest.java:6)
at DatabaseTest.main(DatabaseTest.java:14)
Upvotes: 0
Views: 697
Reputation: 1915
i faced this problem before while working on a project, I put the jar file in 2 locations, what worked for me was as follows:
I put the mysql jar in JAVA_HOME/JRE_FOLDER/lib/ext/
then the other thing is that i create a libs folder inside the project (directly in the project's folder) and also put the mysql jar inside it. After that add the jar (the one inside the libs folder) to the building path of the project.
If you use Eclipse, adding the jar to the building path is done by right-clicking on the jar and choosing "Build Path" from the menu and then choosing "Add to Build Path".
Hope this helps,
Upvotes: 0
Reputation: 6590
You need to add the JAR to your classpath. When launching the java app, simply put:
java -cp mysql-connector-java-5.1.21-bin.jar TheNameOfYourMainClass
Upvotes: 1