MySql Last Insert ID,Connector .net

我正在使用MySql Connector .net,我需要获取上一个查询生成的插入ID。 现在,我假设MySqlHelper.ExecuteNonQuery的返回值应该是最后一个插入ID,但它只返回1。

我正在使用的代码是:

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

但是, insertID始终为1.我尝试创建MySql连接并手动打开/关闭,这导致了相同的行为

1是查询影响的记录,这里只插入一行,因此1返回

要获取插入行的id,必须在sqlserver中使用scope_identity() ,在MySql中使用LAST_INSERT_ID()

只需使用LastInsertedId字段即可

 MySqlCommand dbcmd = _conn.CreateCommand(); dbcmd.CommandText = sqlCommandString; dbcmd.ExecuteNonQuery(); long imageId = dbcmd.LastInsertedId; 

尝试使用此查询来获取最后插入的ID –

 SELECT LAST_INSERT_ID(); 

然后,运行DbCommand.ExecuteReader方法获取IDataReader –

 command.CommandText = "SELECT LAST_INSERT_ID()"; IDataReader reader = command.ExecuteReader(); 

……并从读者那里获取信息 –

 if (reader != null && reader.Read()) long id = reader.GetInt64(0); 

…别忘了关闭读者;-)

我有同样的问题,经过一些测试,我发现问题似乎是连接方法; 您正在使用连接字符串。

这当然是利用自动连接池重用,但在这种情况下它给我带来了麻烦。

对我来说,最终的解决方案是创建一个新连接,执行insert查询,然后执行last_insert_id()。 在同一个连接上。

如果不使用相同的连接,last_insert_id()可能会返回任何内容,我不知道为什么,但猜测它会丢失对事物的跟踪,因为它可能是不同的连接。

例:

 MySqlConnection connection = new MySqlConnection(ConnectionString); connection.Open(); int res = MySqlHelper.ExecuteNonQuery( connection, "INSERT INTO games (col1,col2) VALUES (1,2);"); object ores = MySqlHelper.ExecuteScalar( connection, "SELECT LAST_INSERT_ID();"); if (ores != null) { // Odd, I got ulong here. ulong qkwl = (ulong)ores; int Id = (int)qkwl; } 

我希望这可以帮助别人!