我正在尝试从我的表中删除一个事件。但是我似乎无法让它发挥作用。 我的SQL语句是:
public void deleteEvent(String eventName){
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
db.update(query);
System.out.println (query);
}
使用MySQL db
答案 0 :(得分:4)
尝试使用以下内容:
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
try {
Connection con = getConnection();
Statement s = con.createStatement();
s.execute(query);
} catch (Exception ex) {
ex.printStackTrace();
}
您必须对getConnection()
方法进行编码以返回有效的数据库连接。
答案 1 :(得分:0)
我建议使用Statement.executeUpdate方法,因为它返回一个整数。因此,在执行此删除查询后,如果您确实删除了任何记录,您也将获得信息(在这种情况下,您希望此方法返回1,因为您使用的是LIMIT = 1)。我建议你在不需要时立即关闭Statement,这是骨架实现:
private void performDelete(Connection conn, String deleteQuery, int expectedResult) throws SQLException {
Statement stmt = conn.createStatement();
int result = -1;
try {
result = stmt.executeUpdate(deleteQuery);
if(result != expectedResult) {
//Here you can check the result. Perhaps you don't need this part
throw new IllegalStateException("Develete query did not return expected value");
}
} catch(SQLException e) {
//Good practice if you use loggers - log it here and rethrow upper.
//Or perhaps you don't need to bother in upper layer if the operation
//was successful or not - in such case, just log it and thats it.
throw e;
} finally {
//This should be always used in conjunction with ReultSets.
//It is not 100% necessary here, but it will not hurt
stmt.close();
}
}