java 删除 sql 不删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4983984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
delete sql not deleting
提问by Tuffy G
I'm trying to delete an event from my table. However I can't seem to get it to work. My SQL statement is:
我正在尝试从我的表中删除一个事件。但是我似乎无法让它工作。我的 SQL 语句是:
public void deleteEvent(String eventName){
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
db.update(query);
System.out.println (query);
}
Using MySQL db
使用 MySQL 数据库
回答by Swaranga Sarma
Try using the following :
尝试使用以下方法:
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();
}
You have to code your getConnection()
method to return a valid Database Connection.
您必须对getConnection()
方法进行编码以返回有效的数据库连接。
回答by Sebastian ?askawiec
I would suggest using Statement.executeUpdatemethod, since it returns an integer. So after performing this delete query you will also have information if you really deleted any records (in this case you would expect this method to return 1, since you are using LIMIT=1). I would also suggest closing Statement as soon as you don't need it, here is skeleton implementation:
我建议使用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();
}
}