jdbc to MYSQL error: No suitable driver found for jdbc:mysql://localhost:3306/test?user='root'&password='' [duplicate]

杀马特。学长 韩版系。学妹 提交于 2020-01-22 02:24:07

问题



I have the following code to connect to a mysql db :

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

I am getting the following error:

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


NOTE Some common corrections I found online were:

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

I dont think this is the case with my code.
Thank you.


回答1:


That can happen if you didn't load the driver before making the first connection ever.

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

To be sure, the driver has to go in /WEB-INF/lib, not in /WEB-INF. You've there by the way some SQL injection holes. Look at PreparedStatement. The finally can also be improved, as you have it now, the con will never be closed when rs.close() throws an exception.



来源:https://stackoverflow.com/questions/10612821/jdbc-to-mysql-error-no-suitable-driver-found-for-jdbcmysql-localhost3306-te

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!