使用JdbcTemplate将记录插入数据库时​​出错

时间:2018-04-03 17:48:07

标签: spring-boot spring-jdbc jdbctemplate

当我尝试使用JdbcTemplate.update()将记录插入数据库时​​,我收到错误。

运行“选择”,“更新”,“插入”和“删除”查询时,

JdbcTemplate正常工作。但是当我尝试插入记录并检索生成ID的插入记录时,它才会失败。

我的代码:

public class DBService {
    @Autowired
    private final JdbcTemplate jdbc;

    public int addJob(Job modal) {
        String query = "INSERT INTO JOBS (USERNAME, CREATEDON, STATUS, TYPE, DATA) "
                + "VALUES (?, ?, ?, ?, ?)";

        try {
            logger.trace("Adding job to DB, job type: " + modal.getType() + ", data: " + modal.getData());

            KeyHolder holder = new GeneratedKeyHolder();
            jdbc.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {

                    try(PreparedStatement ps = con.prepareStatement(query, new String[] { "ID"})) {

                        ps.setString(1, modal.getUserName());
                        ps.setTimestamp(2, modal.getCreatedOn());
                        ps.setString(3, modal.getStatus());
                        ps.setString(4, modal.getType());
                        ps.setString(5, modal.getData());

                        return ps;
                    } catch (SQLException ex) {
                        logger.error("addJob: Exception thrown creating prepare statement. Error: " + ex.getMessage(), ex);
                        throw ex;
                    }
                }
            }, holder);

            logger.trace("Successfully added job to DB, job: " + modal.getData() + ", ID: " + holder.getKey());

            return holder.getKey().intValue();

        } catch (DataAccessException e) {
            logger.error("Exception thrown inserting record into table. Error: " + e.getMessage(), e);
        }

        return -1;
    }
}

控制台输出:

DEBUG   2018-04-03 12:10:25,317 [main] org.springframework.jdbc.core.JdbcTemplate [] - Executing SQL update and returning generated keys
DEBUG   2018-04-03 12:10:26,142 [main] org.springframework.jdbc.core.JdbcTemplate [] - Executing prepared SQL statement
INFO    2018-04-03 12:10:59,242 [main] org.springframework.jdbc.support.SQLErrorCodesFactory [] - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
DEBUG   2018-04-03 12:10:59,242 [main] org.springframework.jdbc.support.SQLErrorCodesFactory [] - Looking up default SQLErrorCodes for DataSource [org.apache.tomcat.jdbc.pool.DataSource@5f254608]
DEBUG   2018-04-03 12:10:59,244 [main] org.springframework.jdbc.support.SQLErrorCodesFactory [] - SQL error codes for 'Oracle' found
DEBUG   2018-04-03 12:10:59,244 [main] org.springframework.jdbc.support.SQLErrorCodesFactory [] - Caching SQL error codes for DataSource [org.apache.tomcat.jdbc.pool.DataSource@5f254608]: database product name is 'Oracle'
DEBUG   2018-04-03 12:10:59,244 [main] org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator [] - Unable to translate SQLException with Error code '0', will now try the fallback translator
ERROR   2018-04-03 12:10:59,245 [main] com.sample.projectA.services.DBService [] - Exception thrown inserting record into table. Error: PreparedStatementCallback; uncategorized SQLException for SQL []; SQL state [null]; error code [0]; Statement closed.; nested exception is java.sql.SQLException: Statement closed.
org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL []; SQL state [null]; error code [0]; Statement closed.; nested exception is java.sql.SQLException: Statement closed.
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:84)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
    at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:904)
    at com.sample.projectA.services.DBService.addJob(DBService.java:133)
    at com.sample.projectA.services.test.DBServiceTest.test6_addJob(DBServiceTest.java:162)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.sql.SQLException: Statement closed.
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:110)
    at com.sun.proxy.$Proxy89.executeUpdate(Unknown Source)
    at org.springframework.jdbc.core.JdbcTemplate$3.doInPreparedStatement(JdbcTemplate.java:907)
    at org.springframework.jdbc.core.JdbcTemplate$3.doInPreparedStatement(JdbcTemplate.java:904)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
    ... 33 more

1 个答案:

答案 0 :(得分:1)

您不应关闭jdbc.update(new PreparedStatementCreator内创建的PreparedStatement。 您可以使用try-with资源语法(try(PreparedStatement ps =),这会导致ps在try块完成后立即关闭。

检查https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/PreparedStatementCreator.html#createPreparedStatement-java.sql.Connection-

的javadoc

它声明 JdbcTemplate将关闭创建的语句。

尝试使用PreparedStatementCreatorFactory而不是创建PreparedStatement的实例,您的代码应该变得更短,更易读。