[英]How to solve: No suitable driver found for jdbc:mysql://localhost:3306/sampledb
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我收到此错误,这是我的 Java 代码
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在 cmd 上发生以下错误
You need to load the class driver before getting a connection:您需要在获取连接之前加载类驱动程序:
Class.forName("com.mysql.jdbc.Driver").newInstance();
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.
转到https://dev.mysql.com/downloads/connector/j/8.0.html并下载 jar 文件并放入您的类路径。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.