C# 具有方法值的参数化插入查询
我有两种方法。调用方法glass时,需要在查询中插入值。如何在查询中插入方法的值 我正在使用MVC、C#和SQL Server 我尝试的代码是:在这个方法中调用一个glas方法C# 具有方法值的参数化插入查询,c#,sql,ado.net,C#,Sql,Ado.net,我有两种方法。调用方法glass时,需要在查询中插入值。如何在查询中插入方法的值 我正在使用MVC、C#和SQL Server 我尝试的代码是:在这个方法中调用一个glas方法 RController re = new RController(); re.Glas(C_E); string insert = "INSERT INTO dbo.MEP (R1) VALUES (@code)"; using (SqlCommand command = new SqlCommand(insert,
RController re = new RController();
re.Glas(C_E);
string insert = "INSERT INTO dbo.MEP (R1) VALUES (@code)";
using (SqlCommand command = new SqlCommand(insert, con))
{
command.Parameters.AddWithValue("@code", "HERE METHOD GLAS");
con.Open();
int result = command.ExecuteNonQuery();
}
方法GLAS返回一个字符串。我需要在查询中插入该字符串。查询位于另一个控制器方法(Rcontroller)中
您当前的方法是
void
,不返回任何值。您可以通过ref传递值,或者只需更改方法以返回值:
public string GLAS(string C_E)
{
//more code
string glas1 = "OK";
if (i > 0)
{
glas1 = "OK";
}
else
{
glas1 = "Fail";
}
return glas1;
}
然后你可以像这样使用它:
command.Parameters.AddWithValue("@code", GLAS(C_E));
此外,建议不要使用.AddWithValue
,您可以使用参数。Add()
代替:
command.Parameters.Add("@code", SqlDbType.VarChar).Value = GLAS(C_E);
要详细说明这个问题,你有几个选择。其中一些已经详细阐述。存在以下方法,
Add
,AddWithValue
,以及整个参数集合。这提供了灵活性,但您也提到了返回值
因此,要接近初始参数方面
- 添加:定义参数、SQL中的类型和值。这减轻了潜在的数据库推断问题。您传递的值是一个整数,但SQL认为它应该是定义的十进制数
- AddWithValue:SQL将自动推断类型,只需传递一个值和参数
- 参数集合:预先定义所有参数,然后只需传递到
SqlCommand
public DatabaseContext(IConfiguration configuration) => dbConnection = configuration.GetConnectionString("dbConnection");
public bool Insert(string query, params SqlParameter[] parameters)
{
// If no parameters, then you really are not inserting. Handle exception.
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(connection, query))
{
connection.Open();
command.Parameters.AddRange(parameters);
return (command.ExecuteNonQuery() > 0);
}
}
因此,本质上,您可以调用上下文,传递查询、参数,然后执行查询。但您让它返回一个布尔值,而不是一个条件检查来分配成功或失败。当您调用时,您将知道它成功了,因此您可以传回一个有效的状态代码,即HttpStatusCode.Ok
但是你也可以在工厂中包装,或者在交互时稍微清理一下方法。希望这会有所帮助。当我把返回放在那个地方时,它会给我带来错误,它不能像我那样准确地识别变量glas1do,你必须在if之前定义glas1,并在if内部分配它,你已经在ide if中定义了它,所以它不能在I之外使用如果是我的错,剩下的我会处理。
public DatabaseContext(IConfiguration configuration) => dbConnection = configuration.GetConnectionString("dbConnection");
public bool Insert(string query, params SqlParameter[] parameters)
{
// If no parameters, then you really are not inserting. Handle exception.
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(connection, query))
{
connection.Open();
command.Parameters.AddRange(parameters);
return (command.ExecuteNonQuery() > 0);
}
}