2012-03-30 12 views
9

Scenerio:MySQL Come faccio a recuperare l'ID di LAST_INSERT_ID quando utilizzo INSERISCI IGNORE INTO?

  1. sto inserendo un file CSV nel mio database.
  2. che sto utilizzando il driver JDBC per iterare il file e fare i miei inserti
  3. Una colonna name è fatto in modo da unique inserti non cambiano il tavolo quando stesso valore arriva
  4. sto usando INSERT INTO IGNORE per mantenere il iterazione rottura quando l'evento accade
  5. sto usando LAST_INSERT_ID() per aggiungere come FK nella tabella successiva inserto
  6. ottengo 0 quando INSERT_IGNORE accade

Come posso risolvere questo problema?

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(); 
     } 
    } 

Esempio di file CSV da inserire nel database

US, P1, M, 200, 344 
US, P1, L, 233, 344 
US, P2, M, 444, 556 
MX, Q4, L, 656, 777 

Tabelle: http://sqlfiddle.com/#!2/b5752

+0

Wha t è il problema che stai cercando di risolvere? Se stai facendo "INSERISCI IGNORA" e l'ignora accade, non c'è un inserto quindi non c'è un Last_insert_id per quella transazione. Se si desiderava l'ultimo ID di inserimento precedente, era necessario acquisirlo subito dopo l'inserimento. Ma per il tentativo di inserimento più recente, se non è successo, last_insert_id sarà 0. –

+0

@DMac bene allora come faccio a inserire un inserto in un database quando non vuoi sostituire la colonna esistente quando già esiste? – stackoverflow

+0

@stackoverflow Ho postato una risposta qui sotto che si adatta a mysql. –

risposta

2

Se si desidera ottenere un ID per un inserto successiva, il codice deve prova per un valore 0 di LAST_INSERT_ID e se lo ottiene, fai un SELECT sulla tabella per trovare il valore corretto per l'FK per il tuo inserto.

In pseudo-codice, questo sarebbe simile:

$err = mysql("insert ignore into mytable values ($x, $y)") 
if($err){ 
    do something for an error 
} 
$id = mysql("select last_insert_id()"); 
if($id == 0){ 
    $id = mysql("select id from othertable where condition is true for the record I want to reference in my insert"); 
    if($id == 0){ 
     do something for error 
    } 
} 
mysql("insert into othertable VALUES ($id, other stuff)") 

Dovrete di tradurre che per la propria applicazione e la lingua.

+0

heres my table structure http://sqlfiddle.com/#!2/b5752 e fornirò un esempio del file csv nella modifica sopra riportata – stackoverflow

5

Hai familiarità con la sintassi di MySQL ON DUPLICATE KEY UPDATE?

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

// Results are the same as doing an update. 
// Note the way the PK can be used to avoid an IGNORE. 
s1.executeUpdate("INSERT INTO ORIGIN (ORI_NAME) VALUES(\"" 
      + d.getOriginName() + "\" ON DUPLICATE KEY UPDATE ORI_ID=ORI_ID)"); 

Un esempio pratico qui che coinvolge il mantenimento di indirizzi e-mail non riusciti per un sito:

http://blog.developpez.com/james-poulson/p10016/sql/ne-rien-modifier-en-cas-de-duplicate-key/

Per quanto riguarda il recupero l'ultimo ID inserito il seguente è preso dal mysql Link sopra:

Suppose that id is the AUTO_INCREMENT column. To make LAST_INSERT_ID() meaningful for updates, insert rows as follows: 

INSERT INTO table (a,b,c) VALUES (1,2,3) 
    ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3; 
+2

Questa dovrebbe essere la risposta accettata di sicuro. Funziona perfettamente e salva molte delle logiche altrimenti richieste, ad esempio quelle fornite nella risposta accettata. – teh1

Problemi correlati