No suitable driver found for jdbc:mysql://localhost:3306/sampledb
at java.sql/java.sql.DriverManager.getConnection(Unknown Source)
at java.sql/java.sql.DriverManager.getConnection(Unknown Source)
at MySQLConnectExample2.main(MySQLConnectExample2.java:21)
I'm getting this error and this is my java code
String url1 = "jdbc:mysql://localhost:3306/sampledb";
String user = "root";
String password = "14701";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
every time i'm executing
java -cp mysql-connector-java-5.1.21-bin.jar;. MySQLConnectExample
on cmd the followin error is occurring
You need to load the class driver before getting a connection:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Here is an example.
and the working code:
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/sampledb?" + "user=root&password=14701");
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
You don't have the driver/connector in the classpath. Go to https://dev.mysql.com/downloads/connector/j/8.0.html and download the jar file and put in your classpath.
Something like this:
java -cp .;mysql-connector-java-xx-xx.jar com.xx.xx.yourApp
you also need to load the driver like this:
Class.forName("com.mysql.jdbc.Driver");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.