java JDBC:查明查询是否成功?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13434714/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:42:00  来源:igfitidea点击:

JDBC: Find out if query was successful?

javamysqljdbc

提问by user1795609

I'm using JDBC with mysql. I can get my queries to work great. But for update queries for instance I was wondering if there was any way to determine whether the update was successful for for example if the row could not be found.

我在 mysql 中使用 JDBC。我可以让我的查询工作得很好。但是对于例如更新查询,我想知道是否有任何方法可以确定更新是否成功,例如如果找不到该行。

UPDATE TABLE SET  column =  'newvalue' WHERE  primary_key =2

I would like to get the specific error message if possible, this way I can throw a specific exception as to why the query failed.

如果可能的话,我想获取特定的错误消息,这样我就可以抛出一个特定的异常,说明查询失败的原因。

Thanks for your help.

谢谢你的帮助。

回答by a_horse_with_no_name

executeUpdate() will return the number of rows that were affected by your SQL statement:

executeUpdate() 将返回受 SQL 语句影响的行数:

int rows = stmt.executeUpdate("UPDATE ...");
System.out.println(rows + " rows updated");

Of course you could have found out yourself by simply looking at the JavaDocs:

当然,您可以通过简单地查看 JavaDocs 来发现自己:

Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

返回: (1) SQL 数据操作语言 (DML) 语句的行数或 (2) 0 不返回任何内容的 SQL 语句

回答by Reimeus

executeUpdatereturns the row count of rows affected. You could use this to check that your update was executed successfully:

executeUpdate返回受影响行的行数。您可以使用它来检查您的更新是否成功执行:

PreparedStatement pstmt = con.prepareStatement("UPDATE TABLE ...");
int rowsUpdated = pstmt.executeUpdate(); 
if (rowsUpdated == 0) {
   // handle no update
}