Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of affected rows from JdbcTemplate?

I'm using spring JdbcTemplate to execute a sql query:

JdbcTemplate template = new JdbcTemplate(ds);
template.execute(sqlInsert); //returns void

How could I get the number of effected rows, as the execute() method returns void?

like image 630
membersound Avatar asked Jan 12 '15 12:01

membersound


People also ask

Which method returns the number of rows affected by the execution of a query?

* @return the number of rows affected by the execution of the SQL query. * @exception Failed to execute the SQL query. The execute() method executes the given SQL query, which may return multiple results. This method returns a boolean (true/false).

Which is faster JPA or JdbcTemplate?

JdbcTemplate will most likely be faster when talking about pure query execution, because a JPA implementation will do more stuff: Parse JPQL (assuming you are using that) creating a SQL query out of that. executing it.

What is the return value of JdbcTemplate update?

it will return 1 for success and 0 for failure case so, according to it you can process your logic.

Which among the following can help us to fetch the count of affected rows of a database update operation?

executeUpdate() or execute() followed by getUpdateCount() will return the number of rows matched, not updated, according to the JDBC spec.


2 Answers

Call the update method of JdbcTemplate. It will gives you the number of effected rows as return value.

update

public int update(PreparedStatementCreator psc)
       throws DataAccessException

Description copied from interface: JdbcOperations

Issue a single SQL update operation (such as an insert, update or delete statement) using a PreparedStatementCreator to provide SQL and any required parameters. A PreparedStatementCreator can either be implemented directly or configured through a PreparedStatementCreatorFactory.

Specified by:
update in interface JdbcOperations

Parameters:
psc - object that provides SQL and any necessary parameters

Returns:
the number of rows affected

Throws:
DataAccessException - if there is any problem issuing the update

See Also:
PreparedStatementCreatorFactory

like image 65
Jens Avatar answered Oct 08 '22 15:10

Jens


You can probably use JdbcTemplate.update() for that case. this will return the number of rows updated or deleted.

like image 7
Kalaiarasan Manimaran Avatar answered Oct 08 '22 15:10

Kalaiarasan Manimaran