简体   繁体   中英

JDBC/SQLite batch insert with foreign key constraints

I'm trying to import data from CSV files to a database, but table A has foreign key constraints table B. What I want is to insert the data into A and update the relevant row in B if the foreign key matches a primary key in B (and there are no other issues); otherwise nothing should happen. Currently, I'm doing (a slightly more complicate version of) the following:

PRAGMA foreign_keys = ON;

for (row in b.csv){
    INSERT INTO b
    VALUES ("b_key", NULL, NULL);
}

for (row in a.csv){
    INSERT OR IGNORE INTO a 
    VALUES ("a_key", "b_key", ...);

    UPDATE OR IGNORE b 
    SET x = "X", y = "Y"
    WHERE key = "b_key";
}

The result of this is eventually a.csv will contain a row for which the "b_key" is not in table b, at which point the entire batch update will fail with the exception "foreign key constraint failed." Anyone know a simple (or even not-simple) way that I can get this to work?

1) Switch the order of the INSERT the UPDATE in the second loop. That way, "b" will be set before "a" requires it.

2) Use INSERT OR REPLACE rather than UPDATE for the "b" keys. More on how this works and why it is good at: SQLite - UPSERT *not* INSERT or REPLACE . Basically, you will guarantee that you have the key in "b" before putting anything into the "a" table.

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