用户输入疾病,SQL应该返回患有该疾病的所有患者详细信息。但是我收到了以下错误:
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
SQL Query如下所示。请帮我调试一下。
SELECT patient_personal_details.patient_id,
patient_personal_details.first_name,
patient_personal_details.last_name,
patient_personal_details.gender,
patient_personal_details.occupation,
patient_personal_details.marital_status
FROM patient_personal_details
INNER JOIN patient_medical_details
ON patient_personal_details.patient_id = patient_medical_details.patient_id
WHERE patient_medical_details.disease = ?
以下是代码:
public JTable getAllPatientsByDisease(String disease)throws RemoteException{
JTable table = null;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/hospital_database","root","");
String sql = " SELECT patient_personal_details.patient_id, patient_personal_details.first_name, patient_personal_details.last_name, patient_personal_details.gender, patient_personal_details.occupation, patient_personal_details.marital_status FROM patient_personal_details "
+ " INNER JOIN patient_medical_details "
+ " ON patient_personal_details.patient_id = patient_medical_details.patient_id "
+ " WHERE patient_medical_details.disease = ? ";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, disease);
ResultSet rs = ps.executeQuery(sql);
table = new JTable(buildTableModel(rs));
}
catch(SQLException | ClassNotFoundException e){
System.out.println("Error: "+e);
}
return table;
}
答案 0 :(得分:4)
更新了答案:(现在我们有了代码)
问题在于:
ResultSet rs = ps.executeQuery(sql);
// ----------------------------^^^
删除sql
,只需使用:
ResultSet rs = ps.executeQuery();
通过将SQL指定为参数,您使用的是Statement#executeQuery
,而不是PreparedStatement#executeQuery
。 Statement#executeQuery
按字面意思使用SQL字符串,而不替换参数(基本上就像你没有调用setString
)。 (是的,这不是JDBC人员梦寐以求的设计决定。)
原始答案:
该错误消息的关键位是“... near'?'”这告诉我们您从未在该点设置要替换为查询的值,所以?用字面意思。
您需要使用setString
(如果“疾病”列是文本列)或setInt
等来设置查询的参数。 E.g:
PreparedStatement ps = connection.prepareStatement("SELECT ... WHERE patient_medical_details.disease = ?");
ps.setString(1, "arachnophobia"); // <===
ResultSet rs = ps.executeQuery();
参数编号(有点令人惊讶)从第一个?
开始为1,第二个开始为2,等等。