C# How to pass sql variable

1.7k views Asked by At

I'm trying to insert some values to mysql database via C#

INSERT INTO cliente (column1, column2) VALUES (value1, value2);
set @ultima_pk =  LAST_INSERT_ID();
INSERT INTO cliente_ref (refCol1, refCol2) VALUES (refvalue1, (SELECT @ultima_pk));
INSERT INTO cliente_ref (refCol1, refCol2) VALUES (refvalue1, (SELECT @ultima_pk));

When I test it in mysql only, work perfectly but when I try to insert it via C# I cannot.

Error message:

Parameter '@ultima_pk' must be defined.

But @ultima_pk not is param, is a mysql variable.

Bellow the insert function

public bool insert(string query)
{
    this.conectar();

    cmd = new MySqlCommand(query, this.conexion);

    cmd.ExecuteReader();
    //bool retornar = cmd.ExecuteNonQuery() >= 1 ? true : false;
    bool retornar = true;
    this.desconectar();

    return retornar;
}

The connection is working perfecfly.

Any suggestion How can I pass @ultima_pk inside of query in C#?

1

There are 1 answers

3
Joel Coehoorn On

You need to declare it, and then you don't need to select it:

DECLARE @ultima_pk int;
INSERT INTO cliente (column1, column2) VALUES (value1, value2);
set @ultima_pk =  LAST_INSERT_ID();
INSERT INTO cliente_ref (refCol1, refCol2) VALUES (refvalue1, @ultima_pk);
INSERT INTO cliente_ref (refCol1, refCol2) VALUES (refvalue1, @ultima_pk);

Call it like this:

public bool insert_cliente(string value1, string value2, string refvalue, string refvalue2)
{
    string query = @"
    DECLARE @ultima_pk int;
    INSERT INTO cliente (column1, column2) VALUES (@value1, @value2);
    set @ultima_pk =  LAST_INSERT_ID();
    INSERT INTO cliente_ref (refCol1, refCol2) VALUES (@refvalue1, @ultima_pk);
    INSERT INTO cliente_ref (refCol1, refCol2) VALUES (@refvalue2, @ultima_pk);";

    cmd = new MySqlCommand(query, this.conexion);

    //I had to guess at parameter types/lengths. Use the actual column definitions from your database for this
    cmd.Parameters.Add("@value1", MySqlDbType.VarChar, 50).Value = value1;
    cmd.Parameters.Add("@value2", MySqlDbType.VarChar, 50).Value = value2;
    cmd.Parameters.Add("@refvalue", MySqlDbType.VarChar, 50).Value = refvalue;
    cmd.Parameters.Add("@refvalue2", MySqlDbType.VarChar, 50).Value = refvalue2;

    try 
    { 
        this.conectar();
        return (cmd.ExecuteNonQuery() >= 1);
    }
    finally
    {
        this.desconectar();
    } 
}