2

Am I right when I say that I can only use 1 string sql query for batch processing using PreparedStatement in Java?

For example, this is the batch I want to process using PreparedStatement:

INSERT INTO tbl_Customer VALUES(?,?,?,?)
INSERT INTO tbl_Order VALUES(?,?,?,?,?)

Is there any way to process these statements as a batch? Sorry for my bad English.

Azeem
  • 11,148
  • 4
  • 27
  • 40
Tera Mind
  • 263
  • 4
  • 17
  • 1
    Possible duplicate of [using JDBC preparedStatement in a batch](https://stackoverflow.com/questions/6860691/using-jdbc-preparedstatement-in-a-batch) – Flown Jul 04 '17 at 12:37
  • You can't do both in the same batch. You can, however use two PreparedStatements in parallel. – Maurice Perry Jul 04 '17 at 12:40

1 Answers1

3

You the following template:

PreparedStatement ps = null;

ps = conn.prepareStatement("INSERT INTO tbl_Customer VALUES(?,?,?,?)");
while () { 
    ...
    ps.addBatch();
}
result = ps.executeBatch();
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • I want to insert into 2 different tables. Your code only help add many records into 1 single table. – Tera Mind Jul 04 '17 at 12:43
  • use 1 function but call it twice with 2 SQLs – Ori Marko Jul 04 '17 at 12:44
  • The point of using a batch is it can rollback when there's something wrong with a record. Thus, there's no record is inserted into database. If I use 2 SQLs, the other still is inserted into database, right? – Tera Mind Jul 04 '17 at 12:48
  • 1
    @TeraMind Then you should use [transactions](https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html) if you want to ensure both statements are successfully executed. – Flown Jul 04 '17 at 12:51
  • @Tera Mind. see Flown comment. if you didn't call commit yet and remain in same context rollback will rollback both batches – Ori Marko Jul 04 '17 at 12:53