开发者

Java Oracle Transaction

开发者 https://www.devze.com 2023-04-06 08:13 出处:网络
I want to insert data into a database into different tables. Because of constraints I have to do this in a specific order. That means, first insert into table a, then b, then c , .... and no mixing of

I want to insert data into a database into different tables. Because of constraints I have to do this in a specific order. That means, first insert into table a, then b, then c , .... and no mixing of the tables. But I'm writing a program, which get multiple csv files and should import them into the database, but the program can't know what is the right order. So I thought transaction would be the right way, because I heard, that the data consistency must only exists at the end of the transaction. But that doesn't works

My code looks like that:

Connection connection = DriverManager.getConnection(url, user, pw);
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
开发者_JAVA技巧statement.addBatch("INSERT INTO c ....");
statement.addBatch("INSERT INTO a ....");
statement.addBatch("INSERT INTO b ....");
statement.addBatch("INSERT INTO a ....");
// ...
statement.executeBatch();
statement.close();
connection.commit();

But I will get ORA-02291 (integrity constraint violation) :-(


You need to make the constraint deferrable , this way it is not checked until the commit. There is a good article about it here

> drop table c
table C dropped.
> drop table p
table P dropped.
> create table p (id number primary key)
table P created.
> create table c (id number primary key, p_id number)
table C created.
> alter table c add constraint pk_p foreign key (p_id) references p (id) deferrable
table C altered.
> insert into c values ( 1, 1 )
1 rows inserted.
> insert into p values ( 1 )
1 rows inserted.
> commit
commited.


Transaction won't help you with that problem. You could try to disable the necessary constraints, insert your data and then enable the constraints again.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号