LAST_INSERT_ID() always returns 0 (RMySQL) - separate connection issue

前端 未结 3 1172
猫巷女王i
猫巷女王i 2021-01-18 14:49

Original example as found in some post

According to this post the following SQL statements should give me a vector 1, 2, 2, 2, 2 in the end:



        
相关标签:
3条回答
  • 2021-01-18 15:01

    I found a working solution here. It's also mentioned in stephan mc's reply, but as the second option. The first one didn't work for me, so I figured this might be worth highlighting more.

    Anyways, the trick is to run dbClearResult() between the INSERT and SELECT LAST_INSERT_ID():

    > library("RMySQL")
    > con <- dbConnect(MySQL())
    > dbSendQuery(con, "DROP TABLE IF EXISTS t;")
    > dbSendQuery(con, "CREATE TABLE t (i INT NOT NULL AUTO_INCREMENT PRIMARY KEY);")
    > res <- dbSendQuery(con, "INSERT INTO t VALUES (NULL);")
    
    # doesn't work:
    > dbGetQuery(con, "SELECT LAST_INSERT_ID();")
      LAST_INSERT_ID()
    1                0
    
    # works:
    > dbClearResult(rs)
    > dbGetQuery(con, "SELECT LAST_INSERT_ID();")
      LAST_INSERT_ID()
    1                1
    
    0 讨论(0)
  • 2021-01-18 15:10

    You're inserting NULL values into the Primary Key column. Since you can't have two rows with the same PK, you're probably not actually inserting any real data (which is also probably an error you want to catch). Try:

    dbSendQuery(con, "INSERT INTO t VALUES(5);")
    

    Executing that should give you two different values for last_insert_id.

    Edit: misunderstood. See here for the details on LAST_INSERT_ID. Revised answer: if you don't specify a value in an AUTO_INCREMENT column, then you should get a LAST_INSERT_ID value returned. In that case, try:

    INSERT INTO t DEFAULT VALUES
    
    0 讨论(0)
  • 2021-01-18 15:22

    We found a very interesting solution:

    res <- dbSendQuery(con, "INSERT INTO t VALUES (5);")
    res <- dbSendQuery(con, "SELECT LAST_INSERT_ID();")
    fetch(res)
    

    If it does not work, use a dbClearResult(res) before sending the last id request. For us it worked out.

    0 讨论(0)
提交回复
热议问题