Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Last Insert ID, Connector .net

Tags:

c#

.net

mysql

I'm using the MySql Connector .net, and I need to get the insert id generated by the last query. Now, I assume the return value of MySqlHelper.ExecuteNonQuery should be the last insert id, but it just returns 1.

The code I'm using is:

int insertID = MySqlHelper.ExecuteNonQuery(Global.ConnectionString, 
"INSERT INTO test SET var = @var", paramArray);

However insertID is always 1. I tried creating a MySql connection and opening/closing manually which resulted in the same behaviour

like image 697
Splatbang Avatar asked Dec 15 '11 09:12

Splatbang


People also ask

How do I get the last inserted id in MySQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL.

How do I get last inserted data?

Get ID of The Last Inserted RecordIf we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can get the ID of the last inserted/updated record immediately.

What will be the value of LAST_INSERT_ID () for the newly created table?

With no argument, LAST_INSERT_ID() returns a 64-bit value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement.


2 Answers

Just use LastInsertedId field

MySqlCommand dbcmd = _conn.CreateCommand();
dbcmd.CommandText = sqlCommandString;
dbcmd.ExecuteNonQuery();
long imageId = dbcmd.LastInsertedId;
like image 109
Cioxideru Avatar answered Sep 20 '22 00:09

Cioxideru


1 is the no of records effected by the query here only one row is inserted so 1 returns

for getting id of the inserted row you must use scope_identity() in sqlserver and LAST_INSERT_ID() in MySql

like image 31
Nighil Avatar answered Sep 23 '22 00:09

Nighil