我试图使用prepareStatement将数据插入mysql数据库,但它显示了类似的错误
类型不匹配:无法从java.sql.PreparedStatement转换为com.mysql.jdbc.PreparedStatement
以下是我的代码:
<%@ page import="java.sql.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
// Statement st=connection.createStatement();
PreparedStatement st=null;
String Eid = request.getParameter("Eid");
String Rpswd=request.getParameter("Rpswd");
String uType=request.getParameter("uType");
// String query="insert into login_table(`uid`,`pswd`,`user_type`) values('"+Eid+"','"+Rpswd+"','"+uType+"')";
String query="insert into login_table(`uid`,`pswd`,`user_type`) values(?,?,?)";
st = con.prepareStatement(query);
st.setString(1,Eid);
st.setString(2,Rpswd);
st.setString(3,uType);
// int i= st.executeUpdate(query);
int i= st.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>
它正在获取st = con.prepareStatement(query);
上的错误。
帮帮我,我哪里错了?
注意:这是我第一次使用CreateStatement
中的preparedstatement
,所以建议我哪一个适合代码?。
修复导入并替换
import com.mysql.jdbc.PreparedStatement;
通过
import java.sql.PreparedStatement;
您永远不应该在代码中使用mysql特定的类。标准JDBC类就是您所需要的全部。
关于使用aof prepared stataments,是的,每次需要向查询传递参数时都应该使用它。这是一个健壮性和安全性的问题(阅读有关SQL注入攻击的内容)。
但是JDBC代码和一般的Scriptlet在JSP中没有任何作用。JSP是视图组件,其工作是生成HTML。它们不是数据访问组件。这些应该用Java编写,并通过控制器servlet进行访问。
只需删除
import com.mysql.jdbc.PreparedStatement;
并替换为
import java.sql.PreparedStatement;