Execute multiple SQL statements in java

后端 未结 3 2132
[愿得一人]
[愿得一人] 2021-02-14 02:50

I want to execute a query in Java.

I create a connection. Then I want to execute an INSERT statement, when done, the connection is closed but I wan

3条回答
  •  太阳男子
    2021-02-14 03:01

    There are two problems in your code. First you use the same Statement object (stmt) to execute the select query, and the insert. In JDBC, executing a statement will close the ResultSet of the previous execute on the same object.

    In your code, you loop over the ResultSet and execute an insert for each row. However executing that statement will close the ResultSet and therefor on the next iteration the call to next() will throw an SQLException as the ResultSet is closed.

    The solution is to use two Statement objects: one for the select and one for the insert. This will however not always work by default, as you are working in autoCommit (this is the default), and with auto commit, the execution of any statement will commit any previous transactions (which usually also closes the ResultSet, although this may differ between databases and JDBC drivers). You either need to disable auto commit, or create the result set as holdable over commit (unless that already is the default of your JDBC driver).

提交回复
热议问题