Mysql: Is it safe to use LastInsertId() ?

Created on 28 Oct 2015  路  5Comments  路  Source: go-sql-driver/mysql

If connection is shared between many threads . Is it safe to use LastInsertId() ? Thanks for help

Most helpful comment

I think he means Result.LastInsertId() which is implemented in result.go#L16 which just uses the insertId variable set in Exec() from the result of the executed statement.

So it's perfectly safe to use concurrently because it's stored in the result and has nothing to do with the connections.

All 5 comments

No, it is not - the connection pooling by database/sql makes it unsafe. You can use it in transactions, though.

I think he means Result.LastInsertId() which is implemented in result.go#L16 which just uses the insertId variable set in Exec() from the result of the executed statement.

So it's perfectly safe to use concurrently because it's stored in the result and has nothing to do with the connections.

What is NOT safe is executing this after your insert:

SELECT LAST_INSERT_ID()

Because that might use a different connection because of the pooling.

Yeah, thanks. Exactly what @ErikDubbelboer says.

Thanks for the input i did mean Result.LastInsertId()

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tbdingqi picture tbdingqi  路  7Comments

lunemec picture lunemec  路  7Comments

xuewindy picture xuewindy  路  3Comments

BSick7 picture BSick7  路  8Comments

tanepiper picture tanepiper  路  8Comments