gpt4 book ai didi

mysql - 更新行时出现 SQL 错误

转载 作者:行者123 更新时间:2023-11-30 23:02:45 25 4
gpt4 key购买 nike

正在考虑的表的详细信息:

enter image description here

用于更新行的代码是:

 public void updateEmployeeDetails(Employee employee) {

Connection conn = JDBCUtility.getConnection();

try {
String updateSql = "UPDATE EMPLOYEE_INFO SET emp_name=?, location=?, email=?, dob=? WHERE emp_id=?";

PreparedStatement ps = (PreparedStatement)conn.prepareStatement(updateSql);
ps.setString(1, employee.getEmp_name()); /*all the attributes of employee object are of type String */
ps.setString(2, employee.getLocation());
ps.setString(3, employee.getEmail());
ps.setString(4, employee.getDob());
ps.setString(5, employee.getEmp_id());
ps.executeUpdate(updateSql);

} catch (SQLException e) {
System.out.println(e.getErrorCode());
e.printStackTrace();
}
}

收到错误:

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 '?, location=?, email=?, dob=? WHERE  emp_id=?' at line 1

任何人都可以指出错误,因为我仔细检查了查询字符串中的任何可能错误吗? mysql的varchar(45)兼容Java的String吗?即 ps.setString(column_index, String) 可能是错误的根本原因吗?

调试 1:

考虑到 null 的可能性,我尝试(徒劳地)如下:

//  ps.setString(1, employee.getEmp_name());
// ps.setString(2, employee.getLocation());
// ps.setString(3, employee.getEmail());
// ps.setString(4, employee.getDob());
// ps.setString(5, employee.getEmp_id());

ps.setString(1, "Superman");
ps.setString(2, "Sky");
ps.setString(3, "anymail@dooodle.com");
ps.setString(4, "1-1-0111");
ps.setString(5, "501");
ps.executeUpdate(updateSql);

但仍然显示相同的输出。

最佳答案

我通常会做的是:

private static final String UPDATE_ITEM =
"UPDATE `EMPLOYEE_INFO` SET emp_name=?, location=?, email=?, dob=? WHERE emp_id=?";

public void updateEmployeeDetails(Employee employee) {

Connection conn = null;
PreparedStatement ps = null;

try {

conn = JDBCUtility.getConnection();
ps = conn.prepareStatement(UPDATE_ITEM);
ps.setString(1, employee.getEmp_name()); /*all the attributes of employee object are of type String */
ps.setString(2, employee.getLocation());
ps.setString(3, employee.getEmail());
ps.setString(4, employee.getDob());
ps.setString(5, employee.getEmp_id());
ps.executeUpdate();

} catch (SQLException e) {
System.out.println(e.getErrorCode());
e.printStackTrace();
}
}

但是你能仔细检查一下 employee.getEmp_name() 返回了什么吗?

关于mysql - 更新行时出现 SQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23263928/

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