Reputation: 19
I googled this topic but I have yet to find the answer. I am on AWS Amazon instance running Java trying to run simple java to mysql database. I can access db fine through the mysql command. The error is driving me insane.
Note I am running under /development which happens to have the jar file.
[ec2-user@ip-172-31-16-232 development]$ ls
cProgram.c Java2MySql.class Java2MySql.java mysql-connector-java-5.1.12.jar
[ec2-user@ip-172-31-16-232 development]$ echo $JAVA_HOME
/usr/lib/jvm/java
[ec2-user@ip-172-31-16-232 development]$ java -cp /home/ec2-user/development/mysql-connector-java-5.1.12.jar Java2MySql.java
[ec2-user@ip-172-31-16-232 development]$ java Java2MySql
Where is your MySQL JDBC Driver?
MySQL JDBC Driver Registered!
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/smarteregsBlog
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at Java2MySql.main(Java2MySql.java:21)
Closing connection
Java2MySql.java
public class Java2MySql
{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/myBlog";
String driver = "com.mysql.jdbc.Driver";
String userName = "sam";
String password = "Yoo!";
Connection conn = null;
try {
Class.forName(driver);
}catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
}
System.out.println("MySQL JDBC Driver Registered!");
try{
conn = DriverManager.getConnection(url,userName,password);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
System.out.println("Closing connection");
conn.close();
} catch (Throwable ignore){}
}
}
Upvotes: 0
Views: 1306
Reputation: 8956
Well while compiling the class you don't need to specify the jar in this case so simple this should do the job
javac Java2MySql.java
Change this
java -cp /home/ec2-user/development/mysql-connector-java-5.1.12.jar Java2MySql.java
to
java -cp .:pathOfTheDriverJar/mysql-connector-java-5.1.12.jar Java2MySql
Upvotes: 0
Reputation: 7
Make sure the mysql connector jar is located in your classpath. Copying it in same folder as your class file wont work. Or you can simply copy it to lib folder of your jdk.
Upvotes: 0
Reputation: 68715
It seems you provide the jar only at compile time and not providing the jar class path when you try to execute the code:
javac -cp /home/ec2-user/development/mysql-connector-java-5.1.12.jar Java2MySql.java
I assume it to be a typo javac
and not java
You need to provide the jar path when executing the code as well. So change this
java Java2MySql
to
java -cp .:/home/ec2-user/development/mysql-connector-java-5.1.12.jar Java2MySql
Note: mysql-connector-java-5.1.12.jar is only required at runtime in your case because you are loading the class dynamically.
Upvotes: 1