简体   繁体   中英

Can INSERT and DELETE be added in one single executeBatch

I have hundreds of thousand of lines of text which need to be inserted and amang which there are hundred lines which should be deleted. The text file looks like below:

i 01 ppp
i 02 vvv
i 45 bbb
...
d 05
i 09 mmm
i 21 jjj
....

"i" indecates INSERT, "d" indecates deletes DELETE, the rest text of a lne is data which need be handled.

 insert into t1 (id, name)values(?, ?);
 delete from t1 where id = ?;

once a time I read 1000 lines , addBatch(), and executeBatch() for these "i" head lines, and those "d" head lines handled at last. Is it possible that i add mixed insert and delete batch, then execute them?

thanks.

You need 2 multi-row statements.

INSERT INTO t1 (id, name) VALUES (?, ?), (?, ?) ...;
DELETE FROM t1 WHERE id IN (?, ?, ...);

If you want atomic operation, lock table (statement depends on you DB)

Depending on the database in question, you could try use the merge statement

Take a look at Oracle's Merge statement for example

MERGE INTO bonuses D
  USING (SELECT employee_id, salary, department_id FROM employees
  WHERE department_id = 80) S
  ON (D.employee_id = S.employee_id)
  WHEN MATCHED THEN UPDATE SET D.bonus = D.bonus + S.salary*.01
    DELETE WHERE (S.salary > 8000)
  WHEN NOT MATCHED THEN INSERT (D.employee_id, D.bonus)
    VALUES (S.employee_id, S.salary*0.1)
    WHERE (S.salary <= 8000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM