MySQL有C#问题

时间:2014-12-12 20:01:29

标签: c# mysql ado.net

我正在使用带有C#的MySQL,但我遇到了问题。为什么这段代码不起作用?

MySqlCommand cmd = new MySqlCommand("myConnectionString");

MySqlParameter lastId = new MySqlParameter();
lastId.ParameterName = "@LastID";
lastId.Value = 0;
lastId.Direction = System.Data.ParameterDirection.Output;


this.Command.Parameters.Add(lastId);
this.Command.CommandText = "SET @LastID = LAST_INSERT_ID();";

// You have an error in your SQL syntax; check the manual that 
// corresponds to your MySQL server version for the right syntax 
// to use near '0 = LAST_INSERT_ID()'  
this.Command.ExecuteNonQuery();

1 个答案:

答案 0 :(得分:2)

由于种种原因,上述代码完全错误。

  • 首先,MySqlCommand对象需要与open关联 连接并且在您的代码中没有创建连接, 打开并与命令相关联
  • 其次,检索LAST_INSERT_ID的命令文本是SELECT LAST_INSERT_ID(),不需要为此输出参数,但最重要的是,在您的代码中没有要为其检索LAST_INSERT_ID值的insert命令。
  • 第三,你不要使用ExecuteNonQuery来读回你的值 你可以使用ExecuteScalar

所以

using(MySqlConnection con = new MySqlConnection("myConnectionString"))
using(MySqlCommand cmd = con.CreateCommand());
{
    con.Open();

    // BUILD an unique string with the INSERT INTO 
    // followed by the SELECT (with semicolon to divide)
    string sqlInsertText = @"INSERT INTO yourTable (field1, FieldX) VALUES (value1, ValueX);
                            SELECT LAST_INSERT_ID();";
    cmd.CommandText = sqlInsertText;

    // ExecuteScalar will execute the text of the command and returns the first column of the 
    // first row retrieved by the last statement executed 
    // (in this case the result of SELECT LAST_INSERT_ID()
    object result = cmd.ExecuteScalar();
    if(result != null)
    {

       int lastID = Convert.ToInt32(result);
       .....
    }
}