使用Select的MySQL和JDBC PreparedStatement

时间:2015-10-28 12:48:57

标签: java mysql java-ee servlets jdbc

我尝试运行程序时遇到此异常

  

异常   Caughtcom.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:你   您的SQL语法有错误;检查对应的手册   您的MySQL服务器版本是否在'附近使用正确的语法?并通过   =?”在第1行

当我硬编码值时,我得到了正确的结果。例如:SELECT name, pass from servlettutorial.logintable where name = 'Bill' and pass = 'Gates'运行完全正常。

上面程序中的SQL语法有什么问题?

try{
              Class.forName("com.mysql.jdbc.Driver");
              Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/servlettutorial?"
                      + "user=root&password=carinov");

              String sql = "SELECT name, pass from servlettutorial.logintable where name = ? and pass = ?";
              PreparedStatement stmt = conn.prepareStatement(sql);

              stmt.setString(1, serv_name); 
              stmt.setString(2,serv_pass);

              ResultSet rs = stmt.executeQuery(sql);

              while (rs.next()) {

                    String d_name = rs.getString("name");
                    String d_pass = rs.getString("pass");

                    if(d_name.equals(serv_name) && (d_pass.equals(serv_pass)))
                    {
                            found_match=1;
                            break;
                    }
              }

1 个答案:

答案 0 :(得分:0)

您不应该将SQL查询传递给executeQuery(),因为PreparedStatement已经包含查询和参数。

变化

ResultSet rs = stmt.executeQuery(sql)

ResultSet rs = stmt.executeQuery();