views:

109

answers:

4

How to get how many rows updated with PreparedStatement?

.getUpdateCount() returns 0.

For executeUpdate got error:
error occurred during batching: batch must be either executed or cleared

my code:

updTrans = dataSource.getConnection().prepareStatement("update...");
updTrans.setInt(1, Integer.valueOf(transaksjonstatusid));
...
updTrans.addBatch();
upd = updTrans.executeUpdate();
+3  A: 

Did you try to use:

int n = preparedStatement.executeUpdate();

Here you can find some explanations on how to use a PreparedStatement.

Fanny H.
does executeUpdate() do commit? because i needn't commit oh that phase, i should commit later,as batch update
sergionni
if executeUpdate() is executed in a transaction then no, it does not commit the transaction
matt b
see my edited post,please
sergionni
The commit can be set up through the Connection object, not the Statement. You can use conn.setAutoCommit(false); execute your preparedStatement, then use conn.commit(); and set back the autocommit to true if needed.
Fanny H.
@sergionni `executeUpdate()` doesn't commit unless auto-commit is `true`, I believe. If you want to do a batch update, though, you should be using `addBatch()` and `executeBatch()`. `executeBatch()` returns an `int[]` containing the update counts for each command in the batch.
ColinD
A: 

See The 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

Sean
A: 

getUpdateCount is meant to be used with the execute(String sql) method. You are probably doing this:

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();
Mr. Shiny and New
+2  A: 

You should be using PreparedStatement#executeBatch() when using batches.

...
updTrans.addBatch();
upd = updTrans.executeBatch();

It returns an int[] containing update counts of each batch.

BalusC
yes,you are correct, but it returns [-2] now )
sergionni
The actual return value *may* depend on the JDBC implementation used (more precisely, the JDBC driver used). If you consider it wrong as opposed to the JDBC API documentation (or the JDBC driver specific documentation), then consider posting an issue report at the JDBC driver vendor/maintainer. I can't go in detail since it's unknown which one you're using.
BalusC