如何用Java编写预处理语句

时间:2013-07-25 22:59:55

标签: java servlets jdbc

我想使用getParameter进入Stringint并使用prepareStatement和SQL将它们放入数据库中。它通过setStringsetInt向我提供了错误。

try {
    String id = request.getParameter("clientid");
    String cname = request.getParameter("clientname");
    String address = request.getParameter("address");
    String phonemodel= request.getParameter("phonemodel");
    String imei = request.getParameter("imei");
    String problem = request.getParameter("problem");
    String date2 = request.getParameter("date");
    String comments1= request.getParameter("comments");

    int  clientid = Integer.parseInt(id);
    int imeino  = Integer.parseInt(imei);
    // int date1 = Integer.parseInt(date2);

    Statement pstmt;

    Class.forName("org.apache.derby.jdbc.ClientDriver"); 
    Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app" , "app");

    pstmt=con.prepareStatement("Insert into movilapp(id,clientname,address,modle,imei,problem,date,comments) values(?,?,?,?,?,?,?,?)");
    pstmt.setInt(1,clientid);
    pstmt.setString(2,cname );
    pstmt.setString(3,address);
    pstmt.setString(4,phonemodel);
    pstmt.setInt(5,imeino);
    pstmt.setString(6,problem);
    pstmt.setString(7, comments1);
    pstmt.executeUpdate();
}
catch(Exception e){
    JOptionPane.showMessageDialog(null, e);
}

2 个答案:

答案 0 :(得分:3)

您致电con.prepareStatement以获取PreparedStatement,但之后您将其分配给Statement类型的变量,因此Java不知道有PreparedStatement特定方法setString

通过从

更改pstmt的声明类型,将其分配给实际的PreparedStatement变量
Statement pstmt;

PreparedStatement pstmt;

答案 1 :(得分:1)

* 如果使用Statement则其语法为*

 Statement stmt = null;
 stmt = conn.createStatement( );
 String sql = "UPDATE Employees set age=30 WHERE id=103";
 stmt.executeUpdate(sql);

对于PreparedStatement,它是

PreparedStatement pstmt = null;
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
psmt.setInt(1,30);
psmt.setInt(2,1003);
psmt.executeUpdate(SQL);

所以将Statement pstmt;更改为PreparedStatement pstmt = null;它会起作用。