java中sql的字符串参数和SELECT准备语句

时间:2017-01-29 08:28:09

标签: java sql prepared-statement

我遇到问题>>

编程语言:java 数据库:Mysql数据库

我根据方法>>编写的数据参数编写了一个java代码,用于从数据库中检索记录。

代码是:

public static void Get_patient_data(String Hospital1_ID,String Hospital2_ID {       
   try {
      Connection con = getConnection2();
      PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
         con.prepareStatement(
            "SELECT PatientGender "+
            "FROM patientcorepopulatedtable "+
               "WHERE PatientID = Hospital1_ID LIMIT 1" );
      ResultSet result = statement.executeQuery();
      ArrayList<String> array = new ArrayList<String>();
      while( result.next()) {
         System.out.print("the patient Gender is"  +
            result.getString("PatientGender"));
      }
   }
   catch(Exception e) {
      System.out.println("Error"+e);
   }
}

正如您所看到的那样,问题是来自该方法的来自Hospital1_ID参数..而且,PatientID是一个表中的一列,患者可以填充...

=等于运算符不起作用。

2 个答案:

答案 0 :(得分:2)

试试这个

String query =
   "SELECT PatientGender FROM patientcorepopulatedtable "+
      " WHERE PatientID = ? LIMIT ?";
      PreparedStatement preparedStmt = conn.prepareStatement(query);
      preparedStmt.setString   (1, Hospital1_ID);
      preparedStmt.setInt   (2, 1);
      preparedStmt.executeQuery();

答案 1 :(得分:1)

你可以这样做

PreparedStatement statement = (com.mysql.jdbc.PreparedStatement)
   con.prepareStatement(
      "SELECT PatientGender FROM patientcorepopulatedtable "+
         "WHERE PatientID = ? LIMIT 1");
statement.setString(1, Hospital1_ID);
ResultSet result = statement.executeQuery();

您可以找到更多信息here