Java.sql.SQLException:jdbc:mysql://localhost:3306/dbname找不到合适的驱动程序

53

我有这个Java程序:MySQLConnectExample.java

import java.sql.*;
import java.util.Properties;

public class MySQLConnectExample {
    public static void main(String[] args) {
        Connection conn1 = null;
        Connection conn2 = null;
        Connection conn3 = null;

        try {
            String url1 = "jdbc:mysql://localhost:3306/aavikme";
            String user = "root";
            String password = "aa";

            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null)
                System.out.println("Connected to the database test1");

            String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
                System.out.println("Connected to the database test2");
            }

            String url3 = "jdbc:mysql://localhost:3306/aavikme";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "aa");

            conn3 = DriverManager.getConnection(url3, info);
            if (conn3 != null) {
                System.out.println("Connected to the database test3");
            }
        } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
        }
    }
}

我是这样编译它的:

E:\java mysql code driver>javac MySQLConnectExample.java

E:\java mysql code driver>java -cp mysql-connector-java-3.0.11-stable-bin.jar;.
MySQLConnectExample

我遇到了这个错误:

An error occurred. Maybe user/password is invalid
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/
aavikme
        at java.sql.DriverManager.getConnection(DriverManager.java:596)
        at java.sql.DriverManager.getConnection(DriverManager.java:215)
        at MySQLConnectExample.main(MySQLConnectExample.java:20)

我做错了什么?


你的电脑上是否运行了MySQL?复制数据文件夹是没有用的,必须要运行MySQL服务器。 - fredrik
是的,我在我的系统上运行了MySQL。 - user3416261
相关问题:https://dev59.com/XW035IYBdhLWcg3wNdPg - Pacerier
9个回答

80

确保你首先运行这个:

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

这将强制驱动程序进行注册,以便Java知道如何处理那些数据库连接字符串。

有关更多信息,请参见MySQL Connector 参考文档


1
这是遗留代码,但很可能会解决这个问题,因为这是一个非常老的驱动程序。下载更新版本的驱动程序也很可能使问题消失,而不需要改变代码。 - Gimby
5
编译时错误 找不到类异常!!! - user3416261
这是编译时出现的错误 E:\java mysql code driver>javac MySQLConnectExample.java MySQLConnectExample.java:16: 错误: 未报告的异常ClassNotFoundException; 必须捕获或声明为抛出 Class.forName("com.mysql.jdbc.Driver"); ^ 1 error - user3416261
1
仅供参考。命令行中的-cp参数必须指向驱动程序jar包的完整路径。例如:-cp c:\jars\driverjar.jar;。 - RuntimeException
尽管那行代码不是必需的,但知道驱动程序是否正确加载非常有帮助。 - lepe
显示剩余2条评论

11

你需要加载 jdbc driver。考虑下面的代码。

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

            // connect way #1
            String url1 = "jdbc:mysql://localhost:3306/aavikme";
            String user = "root";
            String password = "aa";

            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {
                System.out.println("Connected to the database test1");
            }

            // connect way #2
            String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
                System.out.println("Connected to the database test2");
            }

            // connect way #3
            String url3 = "jdbc:mysql://localhost:3306/aavikme";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "aa");

            conn3 = DriverManager.getConnection(url3, info);
            if (conn3 != null) {
                System.out.println("Connected to the database test3");
            }
   } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

1
编译时错误,类未找到异常! - user3416261
see my modified answer. - unknown
这是我如何存储数据的方式:http://4.bp.blogspot.com/-ZwT6cx-fjH8/UyHhdxT3OeI/AAAAAAAAACU/S7GmSnHecSs/s1600/java+mysql.jpg - user3416261
我已经添加了 ClassNotFoundException。请尝试一下。 - unknown
3
在线上,执行Class.forName("com.mysql.jdbc.Driver");时出现了java.lang.ClassNotFoundException: com.mysql.jdbc.Driver的异常。该异常表示无法找到com.mysql.jdbc.Driver类。 - Ky -
显示剩余2条评论

7

我遇到了同样的问题,我的代码如下:

private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
private Statement stmt = conn.createStatement();

我没有加载驱动程序类,但是在本地它可以工作,我可以从MySQL查询结果,但是当我部署到Tomcat时它不起作用,并且出现以下错误:

No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud

我看到其他答案发布时,按照下面的方式加载了驱动程序类:

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

现在它可以工作了!我不知道为什么它在本地运行良好,需要你的帮助,非常感谢!


1
我在建立连接之前添加了 Class.forName ... 行。 - So S

5
从一个表中检索数据的示例,该表具有列column1、column2、column3和column4。其中column1和2保存int值,而column3和4保存varchar(10)类型的值。
import java.sql.*; 
// need to import this as the STEP 1. Has the classes that you mentioned  
public class JDBCexample {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    static final String DB_URL = "jdbc:mysql://LocalHost:3306/databaseNameHere"; 
    // DON'T PUT ANY SPACES IN BETWEEN and give the name of the database (case insensitive) 

    // database credentials
    static final String USER = "root";
    // usually when you install MySQL, it logs in as root 
    static final String PASS = "";
    // and the default password is blank

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
    // registering the driver__STEP 2
            Class.forName("com.mysql.jdbc.Driver"); 
    // returns a Class object of com.mysql.jdbc.Driver
    // (forName(""); initializes the class passed to it as String) i.e initializing the
    // "suitable" driver
            System.out.println("connecting to the database");
    // opening a connection__STEP 3
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
    // executing a query__STEP 4 
            System.out.println("creating a statement..");
            stmt = conn.createStatement();
    // creating an object to create statements in SQL
            String sql;
            sql = "SELECT column1, cloumn2, column3, column4 from jdbcTest;";
    // this is what you would have typed in CLI for MySQL
            ResultSet rs = stmt.executeQuery(sql);
    // executing the query__STEP 5 (and retrieving the results in an object of ResultSet)
    // extracting data from result set
            while(rs.next()){
    // retrieve by column name
                int value1 = rs.getInt("column1");
                int value2 = rs.getInt("column2");
                String value3 = rs.getString("column3");
                String value4 = rs.getString("columnm4");
    // displaying values:
                System.out.println("column1 "+ value1);
                System.out.println("column2 "+ value2);
                System.out.println("column3 "+ value3);
                System.out.println("column4 "+ value4);

            }
    // cleaning up__STEP 6
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
    //  handle sql exception
            e.printStackTrace();
        }catch (Exception e) {
    // TODO: handle exception for class.forName
            e.printStackTrace();
        }finally{  
    //closing the resources..STEP 7
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
        System.out.println("good bye");
    }
}

在代码行 Class.forName("com.mysql.jdbc.Driver"); 中:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver - Ky -

4
您可能没有将MySQL connector/J jar文件复制到lib文件夹中,这个文件必须在类路径中。如果您还没有这样做,请告诉我,我会详细解释答案。

3
所有答案都使用Class.forName("my.vandor.Driver");这一行来加载驱动程序。
作为一个更好的选择,您可以使用DriverManager助手类,它提供了一些方法来处理JDBC驱动程序。
您可能想要:
  1. 使用DriverManager.registerDriver(driverObject);将驱动程序注册到其驱动程序列表中。

使用给定的驱动程序管理器进行注册。新加载的驱动程序类应调用registerDriver方法以使自己对DriverManager知道。如果当前已注册驱动程序,则不执行任何操作。

  1. 使用DriverManager.deregisterDriver(driverObject);将其删除。

从DriverManager的已注册驱动程序列表中删除指定的驱动程序。

示例:
Driver driver = new oracle.jdbc.OracleDriver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
// ... 
// and when you don't need anything else from the driver
DriverManager.deregisterDriver(driver);

or better yet, use a DataSource


3
在你的代码中,你少了Class.forName("com.mysql.jdbc.Driver");。这是你缺失的内容,只有这样才能使一切正常工作。

-2

试试这个

String url = "jdbc:mysql://localhost:3306/<dbname>";
String user = "<username>";
String password = "<password>";
conn = DriverManager.getConnection(url, user, password); 

-2

我曾经遇到过类似的问题,只需要确认一下你的Mysql服务器运行的端口,这样就可以解决问题了。

比如说,我的代码是:

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8080/bddventas","root","");

我将字符串更改为

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bddventas","root","");

看这里!!因为我的服务器运行在那个端口,所以这很有效

希望这能有所帮助


默认情况下,MySQL 监听端口 3306。 - LZH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接