如何解决:找不到适合的驱动程序jdbc:mysql://localhost:3306/sampledb

i1icjdpr  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(463)
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上发生以下错误

ni65a41a

ni65a41a1#

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

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

下面是一个例子。
以及工作代码:

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

v1uwarro2#

类路径中没有驱动程序/连接器。去https://dev.mysql.com/downloads/connector/j/8.0.html 下载jar文件并放入类路径。
像这样:

java -cp .;mysql-connector-java-xx-xx.jar com.xx.xx.yourApp

您还需要像这样加载驱动程序:

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

相关问题