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

时间:2018-10-21 10:44:13

标签: java mysql

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上发生跟随错误

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

您在类路径中没有驱动程序/连接器。转到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");