我发现很难在C#MySql中同时插入3个表中[ERROR]必须定义参数'@lastBatch'请提出建议?

问题描述

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的SQL语句中使用变量,必须设置Allow User Variables=true连接字符串选项:https://mysqlconnector.net/connection-options/#AllowUserVariables

如果您使用的是MySqlConnector,则将获得一条有用的异常消息,该消息将提供解决方案。

,

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

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