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

安稳与你 提交于 2019-12-01 18:08:58

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

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
stephan mc

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!