Scenerio:
- I’m inserting a CSV file into my database.
- I’m using jdbc driver to iterate over the file and do the my inserts
- A
namecolumn is madeuniqueso inserts do not change the table when same value arrives - I’m using
INSERT INTO IGNOREto keep the iteration from breaking when event happens - I’m using LAST_INSERT_ID() to add as FK in next table of insert
- I get 0 when
INSERT_IGNOREhappens
How do I do fix this?
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
con.setAutoCommit(false);
Statement s1 = (Statement) con.createStatement();
s1.executeUpdate("INSERT IGNORE INTO ORIGIN (ORI_NAME) VALUES(\""
+ d.getOriginName() + "\")");
Statement s2 = (Statement) con.createStatement();
s2.executeUpdate("INSERT IGNORE INTO STOCK (ORI_ID,S_TITLE) VALUES ("
+ "(SELECT ORI_ID FROM ORIGIN WHERE ORI_ID =LAST_INSERT_ID()),\""
+ d.getStockTitle() + "\")");
}
con.commit();
}
catch (Exception e)
{
if (con != null)
try
{
con.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
e.printStackTrace();
}
finally
{
if (con != null)
try
{
con.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
Example of CSV file to be inserted into the database
US, P1, M, 200, 344
US, P1, L, 233, 344
US, P2, M, 444, 556
MX, Q4, L, 656, 777
Tables: http://sqlfiddle.com/#!2/b5752
If you want to get an ID for a subsequent insert, your code has to test for a 0 value of LAST_INSERT_ID and if it gets it, do a SELECT on the table to find the right value for the FK for your insert.
In pseudo-code, this would look like:
You’ll have to translate that to your own application and language.