Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ID of the last inserted row in MySQL and Go?

Tags:

mysql

go

How can I use this trick: How to get ID of the last updated row in MySQL? in Go (golang)?

I am using the go-sql-driver. It should work with these two queries but how can I do it in Go?

INSERT INTO table (unique_id) VALUES ("test")
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);

SELECT LAST_INSERT_ID();
like image 503
Kaah Avatar asked May 22 '17 22:05

Kaah


People also ask

How do I get the last row inserted id in MySQL?

MySQL LAST_INSERT_ID() Function The LAST_INSERT_ID() function returns the AUTO_INCREMENT id of the last row that has been inserted or updated in a table.

How do I find the last ID of a MySQL database?

How to get last inserted id of a MySQL table using LAST_INSERT_ID() We will be using the LAST_INSERT_ID() function to get the last inserted id. Last_insert_id() MySQL function returns the BIG UNSIGNED value for an insert statement on an auto_increment column.

How do I get the latest inserted record ID in SQL?

To get an ID of last inserted record, you can use this T-SQL: INSERT INTO Persons (FirstName) VALUES ('Joe'); SELECT ID AS LastID FROM Persons WHERE ID = @@Identity; You can use query like this inside stored procedure or as an ad-hoc query.


1 Answers

Working solution. It is as simple as that. I hope someone else will find this useful:

stmt, err := db.Prepare("INSERT table SET unique_id=? ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)")

res, err := stmt.Exec(unique_id)

lid, err := res.LastInsertId()
like image 128
Kaah Avatar answered Oct 17 '22 18:10

Kaah