C#如何传递sql变量

时间:2015-06-14 20:51:59

标签: c# mysql sql tsql sqlcommand

我试图通过C#

向mysql数据库插入一些值
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));

当我在mysql中测试它时,工作得很好但是当我尝试通过C#插入它时我不能。

错误讯息:

Parameter '@ultima_pk' must be defined.

但是@ultima_pk不是param,是一个mysql变量。

插入插入功能

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;
}

连接工作正常。

任何建议如何在C#中传递查询内的@ultima_pk?

1 个答案:

答案 0 :(得分:0)

您需要声明它,然后您不需要选择它:

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);

这样称呼:

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();
    } 
}