【问题标题】:I'm finding it hard to insert into 3 tables at the same time in C# MySql [ERROR] 'Parameter '@lastBatch' must be defined. Please Suggest?我发现很难在 C# MySql [ERROR] 'Parameter '@lastBatch' 必须定义中同时插入 3 个表。请建议?
【发布时间】:2020-09-24 22:49:33
【问题描述】:

INSERT INTO 查询在 MySql 工作台中有效,但在 c# 中无效。

try
{
    connection.Open();
    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = connection;
    cmd.CommandText = "INSERT INTO product_batch(batchNumber) VALUES(@batchNumber); SET @lastBatch = last_insert_id();  INSERT INTO company(nameCompany) VALUES(@nameCompany); SET @lastCompany = last_insert_id();  INSERT INTO product(name, purchase_price, sale_price, idBatch,idCompany) VALUES(@name, @purchase_price, @sale_price, lastBatch, lastCompany)";
    cmd.Prepare();
    cmd.Parameters.AddWithValue("@name", textBoxItemName.Text);
    cmd.Parameters.AddWithValue("@purchase_price", textBoxCostPrice.Text);
    cmd.Parameters.AddWithValue("@sale_price", textBoxSalePrice.Text);
    cmd.Parameters.AddWithValue("@batchNumber", textBoxBatchNum.Text);
    cmd.Parameters.AddWithValue("@nameCompany", textBoxCompany.Text);
    cmd.ExecuteNonQuery();
    MessageBox.Show("Saved Successfully ");
    connection.Close();
    dataGridDisplay();
    addNewProductFunction();
    functionReadOnlyTrue();
}

This is the error I got

【问题讨论】:

  • 不要发布错误消息的图片。粘贴文本
  • 这是错误:MySql.Data.MySqlClient.MySqlException:'在命令执行过程中遇到致命错误。' 内部异常 .. MySqlException: 必须定义参数'@lastBatch'。
  • 你可以而且应该edit这个问题来添加这些重要信息。
  • 欢迎来到 SO。请阅读How do I ask a good question?

标签: c# mysql sql windows workbench


【解决方案1】:

要在 MySQL 的 SQL 语句中使用变量,您必须设置 Allow User Variables=true 连接字符串选项:https://mysqlconnector.net/connection-options/#AllowUserVariables

如果您使用的是MySqlConnector,您会收到一条有用的异常消息,该消息会提供解决方案。

【讨论】:

    【解决方案2】:

    我在连接字符串中设置了Allow User Variables = true。 其次,问题出在 MySql 数据库中的数据类型

    否则我的代码运行良好。现在问题已经解决了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多