Search code examples
c#mysqlsqlwindowsworkbench

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?


This INSERT INTO query is working in MySql workbench, but not in 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


Solution

  • I set Allow User Variables = true in the connection string. Secondly the problem was with the datatype in the MySql database.

    otherwise my code was working perfectly. now the problem has been resolved!