Java 获取用 PreparedStatement 更新的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3711866/
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
Get number of rows updated with PreparedStatement
提问by sergionni
How to get how many rows updated with PreparedStatement?
如何使用 PreparedStatement 更新多少行?
.getUpdateCount()
returns 0.
.getUpdateCount()
返回 0。
For executeUpdate
got error:
error occurred during batching: batch must be either executed or cleared
对于executeUpdate
得到错误:批处理期间发生错误:
必须执行或清除批处理
my code:
我的代码:
updTrans = dataSource.getConnection().prepareStatement("update...");
updTrans.setInt(1, Integer.valueOf(transaksjonstatusid));
...
updTrans.addBatch();
upd = updTrans.executeUpdate();
采纳答案by BalusC
You should be using PreparedStatement#executeBatch()
when using batches.
PreparedStatement#executeBatch()
使用批处理时应该使用。
...
updTrans.addBatch();
upd = updTrans.executeBatch();
It returns an int[]
containing update counts of each batch.
它返回int[]
包含每个批次的更新计数。
回答by Fanny H.
Did you try to use:
您是否尝试使用:
int n = preparedStatement.executeUpdate();
Here you can find some explanations on how to use a PreparedStatement.
在这里您可以找到有关如何使用PreparedStatement 的一些说明。
回答by Sean
See The Javadoc
请参阅Javadoc
public int executeUpdate() throws SQLException
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Returns: either (1) the row count for INSERT, UPDATE, or DELETE statements or (2) 0 for SQL statements that return nothing
Throws: SQLException - if a database access error occurs or the SQL statement returns a ResultSet object
public int executeUpdate() 抛出 SQLException
执行此 PreparedStatement 对象中的 SQL 语句,该语句必须是 SQL INSERT、UPDATE 或 DELETE 语句;或不返回任何内容的 SQL 语句,例如 DDL 语句。
返回: (1) INSERT、UPDATE 或 DELETE 语句的行数或 (2) 0 用于不返回任何内容的 SQL 语句
抛出: SQLException - 如果发生数据库访问错误或 SQL 语句返回 ResultSet 对象
回答by u7867
getUpdateCount
is meant to be used with the execute(String sql)
method. You are probably doing this:
getUpdateCount
旨在与该execute(String sql)
方法一起使用。你可能正在这样做:
String sql = "UPDATE some_table SET somecolumn = ? WHERE someId = ?";
PreparedStatement ps = connection.prepare(sql);
ps.setString(1, val);
ps.setInt(2, id);
ps.executeUpdate();
In that case you should simply do
在这种情况下,你应该简单地做
int rowsUpdated = ps.executeUpdate();