gpt4 book ai didi

java - : No suitable driver found for jdbc:mysql://localhost:3306/sampledb如何解决

转载 作者:行者123 更新时间:2023-11-29 07:28:02 34 4
gpt4 key购买 nike

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)

我收到这个错误,这是我的 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");
}

每次执行

java -cp mysql-connector-java-5.1.21-bin.jar;. MySQLConnectExample

在 cmd 上发生以下错误

最佳答案

您需要在获得连接之前加载类驱动程序:

Class.forName("com.mysql.jdbc.Driver").newInstance();

Here是一个例子。

和工作代码:

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();
}
}
}

关于java - : No suitable driver found for jdbc:mysql://localhost:3306/sampledb如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52914454/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com