如何获取我刚刚插入到C#中的mysql数据库中的对象的id?

时间:2012-06-26 16:38:23

标签: c# mysql

我正在尝试检索我刚刚引入数据库的对象的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();

任何帮助都会受到赞赏,即使它不是最终解决方案:)非常感谢!

4 个答案:

答案 0 :(得分:5)

查询结尾处有一个额外的括号。

更改此

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());

答案 1 :(得分:1)

如果你真的写了:

SELECT last_insert_id() AS id)

你必须删除最后的),这会导致语法错误。

答案 2 :(得分:1)

从while循环中删除reader.Read();

使用executescalar代替executereader

int no = convert.toint32( command.ExecuteScalar( "SELECT last_insert_id() AS id"));

答案 3 :(得分:1)

我会在插入语句后添加它。

command.CommandText = "INSERT ...  ; select last_insert_id();";

然后使用它来获得结果:

int id = Convert.ToInt32(command.ExecuteScalar());
相关问题