如何使用预准备语句从数据库中选择实体

时间:2014-12-11 13:07:38

标签: java mysql

在尝试添加可能具有相同密钥的学生之前,我正在尝试检查数据库中是否存在某个密钥。我有一个名为DataBaseHandler的类,它具有操作数据库的功能。如果给定的id存在,则studentAlreadyExist函数返回true,否则返回false。当我尝试运行应用程序时,它给了我这个错误

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
*******

以下是我的代码片段,用于测试学生是否存在

//check if the student exist
public boolean studentAlreadyExists(String id) throws SQLException{
   //first connect to the database;
   connectToDataBase(); 

   selectSQL = "select name from student where idNumber like ?";
   prstmt = con.prepareStatement(selectSQL);
   prstmt.setString(1, id);

   ResultSet rs = prstmt.executeQuery(selectSQL);
   String dbname = null;
   while(rs.next()){

       dbname = rs.getString("name");
   }

    return dbname != null;
}

2 个答案:

答案 0 :(得分:0)

执行selectSQL时,不要将executeQuery作为参数传递(再次)。

答案 1 :(得分:0)

您之前已经准备好了,您不必再将queryString作为参数传递。

API: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery()

应该是这样的:

public boolean studentAlreadyExists(String id) throws SQLException{
   connectToDataBase(); 

   selectSQL = "select name from student where idNumber like ?";
   prstmt = con.prepareStatement();
   prstmt.setString(1, id);

   /* Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.*/
   ResultSet rs = prstmt.executeQuery();
   String dbname = null;
   while(rs.next()){

       dbname = rs.getString("name");
   }

    return dbname != null;
}