我正在尝试检索我刚刚引入数据库的对象的 ID,但它不起作用(我总是遇到异常)并且这不是因为查询,显然它工作正常。我已经尝试了我在网上找到的其他方法,但都没有用。这是我使用的代码(C# 和数据库是 MySql)
conn.Open();
command = conn.CreateCommand();
command.CommandText = //here it goes the insert command which works perfectly
command.ExecuteNonQuery();
//Last object's id is retrieved
command = conn.CreateCommand();
command.CommandText = "SELECT last_insert_id() AS id)";
reader = command.ExecuteReader();
while (reader.Read())
{
reader.Read();
MessageBox.Show(reader["id"].ToString());
}
conn.Close();
即使不是最终解决方案,我们也将不胜感激 :) 非常感谢!
最佳答案
您在查询末尾有一个额外的括号。
改变这个
command.CommandText = "SELECT last_insert_id() AS id)";
到:
command.CommandText = "SELECT last_insert_id() AS id";
然后您从第一条记录读取到第二条记录,但只有一条记录。
改变这个:
while (reader.Read())
{
reader.Read();
MessageBox.Show(reader["id"].ToString());
}
到:
reader.Read();
MessageBox.Show(reader["id"].ToString());
关于c# - 在 C# 中,如何获取刚刚插入到 mysql 数据库中的对象的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11211990/