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
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
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.