gpt4 book ai didi

java - SQL 语句和准备语句错误

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:46 25 4
gpt4 key购买 nike

用户输入一种疾病,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查询如下图所示。请帮我调试一下。

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;
}

最佳答案

更新后的答案:(现在我们有了代码)

问题出在这里:

ResultSet rs = ps.executeQuery(sql);
// ----------------------------^^^

删除sql,只需使用:

ResultSet rs = ps.executeQuery();

通过将 SQL 指定为参数,您使用的是 Statement#executeQuery , 不是 PreparedStatement#executeQuery . Statement#executeQuery 按字面意义使用 SQL 字符串,而不替换参数(基本上就像您没有调用 setString 一样)。 (是的,这不是 JDBC 人员的绝妙设计决定。)


原始答案:

该错误消息的关键位是 “...near '?'” 这告诉我们您从未设置要在此时替换到查询中的值,因此 ?按字面意思使用。

您需要使用 setString (如果“疾病”列是文本列)或 setInt 等,为查询设置参数。例如:

PreparedStatement ps = connection.prepareStatement("SELECT ... WHERE patient_medical_details.disease = ?");
ps.setString(1, "arachnophobia"); // <===
ResultSet rs = ps.executeQuery();

参数的编号(有点令人惊讶)第一个 ? 以 1 开始,第二个以 2 开始,依此类推。

关于java - SQL 语句和准备语句错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30600015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com