According to this post the following SQL statements should give me a vector
1, 2, 2, 2, 2
in the end:
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