gpt4 book ai didi

c# - 如何在用于 SQL 插入的方法中进行参数化查询?

转载 作者:行者123 更新时间:2023-11-30 22:21:58 26 4
gpt4 key购买 nike

我真的不知道如何在标题中很好地解释它,但这是我的问题。

在许多重载方法中,我创建了这个方法,它的唯一目的是将给定值插入到给定表中:

public static int Insert(string cs, string table, string[] values)
{
using (SqlConnection con = new SqlConnection(cs))
{
try
{
string strCommand = string.Format(
"INSERT INTO {0} VALUES ({1})",
table,
values.Aggregate((a, b) => (a + ", " +b)));
SqlCommand com = new SqlCommand(strCommand, con);
con.Open();
int result = com.ExecuteNonQuery();
return result;

}
catch (SqlException ex)
{
HttpContext.Current.Response.Write(ex.Message);
return 0;
}
}
}

现在它没有使用参数化查询,不是吗?

我真的很想在其中实现这个概念,但我不知道如何实现。

最佳答案

您可以使用包含列名及其各自值的字典

   Dictionary<string, object> values = new Dictionary<string,object>();
values.Add("userid", 1022);
values.Add("username", "JFord");
values.Add("IsActive", 0);
string table = "users";

用法:

MyClass.Insert("connection", "users", values);

方法

public static int Insert(string cs, string table, Dictionary<string,object> values)
{
string strCommand = string.Format("INSERT INTO {0} VALUES ({1})",
table, "@"+String.Join(", @", values.Keys));

//strCommand becomes: "INSERT INTO users VALUES (@userid, @username, @IsActive)"

SqlCommand com = new SqlCommand(strCommand, conn);

foreach (string key in values.Keys)
{
com.Parameters.AddWithValue("@" + key, values[key]);
}

}

关于c# - 如何在用于 SQL 插入的方法中进行参数化查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14034249/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com