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

前端 未结 3 1171
猫巷女王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
    

提交回复
热议问题