JdbcTemplate API备忘

Spring的JdbcTemplate的API中常用的二个方法:

1. boolean execute(String sql) throws SQLException; //executes an SQL statement and indicates the form of the first result, true if the first result is a ResultSet  object; false if it is an update count or there are   no results.   我的理解是execute并不关心返回的结果。当然你可以判断返回值,不过应用程序很少这样的使用。

   

2.int executeUpdate(String sql) throws SQLException; //用于执行DML or DDL的方法。

二种返回值:

1.the row count for SQL Data Manipulation Language (DML) statements

2.0 for SQL statements that return nothing。

对于一些sql有ResultSet返回时,即并不是insert,delete,update 也不是return nothing的sql时,该方法会抛异常,比如下面的更新序列的sql由于有ResultSet返回,所以应该使用execute方法。

Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: StatementCallback; SQL [select setval('t_ddtourism_post_id_seq',( select MAX(id)+1 from t_ddtourism_post ), false)]; 传回预期之外的结果。; nested exception is org.postgresql.util.PSQLException: 传回预期之外的结果。
    at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:100)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:407)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:522)
    at com.daodao.tool.migrate.service.SequenceReset.resetSquences(SequenceReset.java:26)
    at com.daodao.tool.migrate.App.main(App.java:59)
Caused by: org.postgresql.util.PSQLException: 传回预期之外的结果。
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:305)
    at org.springframework.jdbc.core.JdbcTemplate$1UpdateStatementCallback.doInStatement(JdbcTemplate.java:512)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:396)
    ... 3 more

 
原文地址:https://www.cnblogs.com/highriver/p/2425837.html