我编写此代码来更新derby数据库中的患者,但它会抛出SQLSyntaxErrorException
。我错过了什么吗?
public void updateInDatabase(int ID,String sex, String firstName, String familyName, String eMail) {
try {
String sql = "UPDATE PATIENT SET sex = "+ sex +" WHERE NR = "+ID;
st.executeUpdate(sql);
String sq2 = "UPDATE PATIENTEN SET FIRSTNAME=" + firstName + "WHERE NR=" + ID;
st.executeUpdate(sq2);
String sq3 = "UPDATE PATIENTEN SET FAMILYNAME=" + familyName + "WHERE NR=" + ID;
st.executeUpdate(sq3);
String sq4 = "UPDATE PATIENTEN SET EMAIL=" + eMail + "WHERE NR=" + ID;
st.executeUpdate(sq4);
} catch (SQLException ex) {
Logger.getLogger(DbManagerPatienten.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 0 :(得分:2)
你的主要错误是你使用字符串连接,这会让你容易受到SQL Injection攻击。
您的具体错误是您没有引用文字值。
String sql = "UPDATE PATIENT SET sex = "+ sex +" WHERE NR = "+ID;
该Java语句导致sql
具有以下SQL语句:
UPDATE PATIENT SET sex = male WHERE NR = 42
陈述应该是:
UPDATE PATIENT SET sex = 'male' WHERE NR = 42
但是,在Java中执行此操作的正确方法是使用PreparedStatement
,并使用try-with-resources。
有关详细信息,请参阅以下内容:
String sql = "UPDATE PATIENT" +
" SET SEX = ?" +
", FIRSTNAME = ?" +
", FAMILYNAME = ?" +
", EMAIL = ?" +
" WHERE NR = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, sex);
stmt.setString(2, firstName);
stmt.setString(3, familyName);
stmt.setString(4, eMail);
stmt.setInt (5, ID);
int updateCount = stmt.executeUpdate();
if (updateCount == 0)
throw new IllegalArgumentException("Patient not found: " + ID);
}