问题描述
我有以下代码可连接到mysql db:
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();
}
}
}
我遇到以下错误:
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.
推荐答案
如果您在进行首次连接之前未加载驱动程序,则可能会发生这种情况.
That can happen if you didn't load the driver before making the first connection ever.
Class.forName("com.mysql.jdbc.Driver");
可以肯定的是,驱动程序必须进入/WEB-INF/lib
,而不是进入/WEB-INF
.顺便说一下,您那里有一些SQL注入漏洞.看PreparedStatement
. finally
也可以进行改进,就像现在一样,con
不会在rs.close()
引发异常时关闭.
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.
这篇关于jdbc到MYSQL错误:找不到适用于jdbc:mysql://localhost:3306/test的驱动程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!