【问题标题】:jdbc to MYSQL error: No suitable driver found for jdbc:mysql://localhost:3306/test?user='root'&password='' [duplicate]jdbc 到 MYSQL 错误:找不到适合 jdbc 的驱动程序:mysql://localhost:3306/test?user='root'&password='' [重复]
【发布时间】:2012-05-23 16:16:35
【问题描述】:


我有以下代码可以连接到 mysql 数据库:

public static void insertIntoDatabase(String code,String name,String temp,String hum,String del) {
    Connection con = null;
    ResultSet rs = null;

    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "";

    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection(url, user, password);
        rs = con.prepareStatement("CREATE TABLE IF NOT EXISTS AiportDetails(code VARCHAR(50) PRIMARY KEY, " +
                "name VARCHAR(50), temp VARCHAR(50), hum VARCHAR(50), del VARCHAR(50)) ENGINE=InnoDB;").executeQuery();
        rs = con.prepareStatement("INSERT INTO AirportDetails(code,name,temp,hum,del) VALUES("+code+","+
                name+","+temp+","+hum+","+del+");").executeQuery();
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

我收到以下错误:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


注意 我在网上找到的一些常见更正如下:

1. The driver is not in the /WEB-INF/lib folder.
2. The url is wrong.

我认为我的代码不是这种情况。
谢谢。

【问题讨论】:

    标签: mysql jsp jdbc sqlexception


    【解决方案1】:

    如果您在第一次连接之前没有加载驱动程序,就会发生这种情况。

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

    可以肯定的是,驱动程序必须进入/WEB-INF/lib,而不是/WEB-INF。顺便说一句,您已经找到了一些 SQL 注入漏洞。看看PreparedStatementfinally 也可以改进,就像你现在拥有的那样,当rs.close() 抛出异常时,con 将永远不会关闭。

    【讨论】:

    • 嗨。对不起。它位于 /WEB-INF/lib 文件夹中。现在我得到一个 ClassNotFoundException。可能是什么问题?
    猜你喜欢
    • 2014-04-18
    • 2015-03-28
    • 2017-12-11
    • 2021-03-23
    • 2013-02-08
    • 2020-10-17
    • 2014-06-18
    • 1970-01-01
    • 2016-09-07
    相关资源
    最近更新 更多