与这篇文章相关的问题,我认为他离线了,所以我无法收到任何关于atm的反馈:
MySql and inserting last ID problem remains
我不确定我是否完全盲目,但是在这段代码中:
// run the insert using a non query call
command.CommandText = cmd.ToString();
command.ExecuteNonQuery();
/* now we want to make a second call to MYSQL to get the new index
value it created for the primary key. This is called using scalar so it will
return the value of the SQL statement. We convert that to an int for later use.*/
command.CommandText = "select last_insert_id();";
id = Convert.ToInt32(command.ExecuteScalar());
//------- the name id does not exist in the current context
// Commit the transaction.
transaction.Commit();
}
catch (Exception ex)
{
Label10.Text = ": " + ex.Message;
try
{
// Attempt to roll back the transaction.
transaction.Rollback();
}
catch
{
// Do nothing here; transaction is not active.
}
}
}
id未设置为任何内容,我不确定他是如何尝试将其设置为最后插入的id?
编辑:
int id = Convert.ToInt32(cmd.ExecuteScalar());
Label10.Text = Convert.ToString(id);
最佳答案
您应该能够使用select @@IDENTITY;
返回插入记录的ID,而不必使用第二个查询:
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); select @@IDENTITY;"
int id = Convert.ToInt32(cmd.ExecuteScalar());
复习您的旧问题后,此方法应相同:
OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email) VALUES ('rusty@msn.com'); SELECT LAST_INSERT_ID();"
int id = Convert.ToInt32(cmd.ExecuteScalar());