C# 如何传递 sql 变量
本文关键字:变量 sql 何传递 | 更新日期: 2023-09-27 17:56:03
我正在尝试通过 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不是参数,它是一个 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传递到查询内部?
您需要声明它,然后不需要选择它:
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();
}
}