【问题标题】:MySQL with C# problems [closed]有 C# 问题的 MySQL [关闭]
【发布时间】:2014-12-12 20:01:28
【问题描述】:

我正在使用带有 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();

【问题讨论】:

  • 你告诉我们为什么?什么不起作用?你得到什么错误?您尝试过什么来解决此问题?
  • 一方面,@LastID 是您传入的参数,但您试图将其设置为变量。就像错误所说的那样,您正在尝试将 LAST_INSERT_ID() 的值分配给另一个值 0。
  • Select LAST_INSERT_ID()var lastId = Command.ExecuteScalar(); 怎么样。不需要out参数?

标签: c# mysql ado.net


【解决方案1】:

上面的代码完全是错误的,原因有很多。

  • 首先,MySqlCommand 对象需要关联一个打开的 连接并且在您的代码中没有创建连接, 打开并与命令关联
  • 其次,检索 LAST_INSERT_ID 的命令文本是 SELECT LAST_INSERT_ID(),不需要为此提供输出参数,但最重要的是,在您的代码中没有您要检索 LAST_INSERT_ID 值的插入命令。
  • 第三,在你的 如果你可以使用 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);
       .....
    }
}

【讨论】:

  • 非常感谢。你帮了我很多!
猜你喜欢
  • 2017-01-17
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多