Serverless MySQL 5.6 w/ Data API - Safely select last inserted record?

0

I'm using Aurora Serverless MySQL 5.6, and my schema has a table with an INT AUTO_INCREMENT primary key. I want to insert a record and return it from a NodeJS lambda function, so I wrote some code like this using the Data API:

rds.executeStatement('INSERT INTO table VALUES(...)"); // #1
rds.exeucteStatement('SELECT * from table WHERE id = LAST_INSERT_ID()'); // #2

However I observed that if multiple users are using the system at the same time, sometimes the LAST_INSERT_ID() in #2 does not return the ID created in #1. I believe this is because using the Data API, #1 and #2 aren't guaranteed to share the same database connection.

Is there anything I can do to make this INSERT/SELECT pattern work as expected using INT primary keys and the Data API? If I did SELECT MAX(id)... in a transaction with the INSERT would that work? Otherwise I'm not sure what else I can do besides move to UUID primary keys, which I've read can be a performance problem for MySQL.

Thank you!

mattwms
質問済み 4年前377ビュー
2回答
0

For anyone who comes across this: the generated AUTO_INCREMENT ID is returned in the generatedFields section of the ExecuteStatement response (i.e. generatedFields[0].longValue). That works fine for my needs.

mattwms
回答済み 4年前
0

CAREFUL! The generatedFields will always only contain the FIRST inserted id even though you might have inserted 500 rows.

回答済み 2年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ