我是编码新手,正在寻找有关如何将多个值传递给内联 SQL 查询中的单个参数的帮助。我设计了以下查询,但我听说这可能会导致 SQL 注入(inject)问题。请帮助我如何使用基于 SQL 查询的参数构建以下内容。
string query = "Select ID, email FROM DBTABLE WHERE email in (";
var stringBuiler = new StringBuilder();
using (StringReader stringReader = new StringReader(DownloadIDtextBox.Text))
{
string line;
string prefix = "";
while ((line = stringReader.ReadLine()) != null)
{
stringBuiler.Append(prefix);
prefix = ",";
stringBuiler.Append("'" + line + "'");
}
}
query += stringBuiler.ToString() + ")";
SqlDataAdapter da = new SqlDataAdapter(query, Connection);
DataTable dt = new DataTable();
da.Fill(dt);
只是想提一下,ID 是 GUID 格式。
最佳答案
如果您手动执行此操作,则过程(基本上)是:
var stringBuiler = new StringBuilder("Select ID, email FROM DBTABLE WHERE email in (");
// create "cmd" as a DB-provider-specific DbCommand instance, with "using"
using (...your reader...)
{
int idx = 0;
...
while ((line = stringReader.ReadLine()) != null)
{
// ...
Guid val = Guid.Parse(line);
// ...
var p = cmd.CreateParameter();
p.Name = "@p" + idx;
p.Value = val;
if (idx != 0) stringBuiler.Append(",");
stringBuiler.Append(p.Name);
cmd.Parameters.Add(cmd);
idx++;
}
}
cmd.CommandText = stringBuiler.Append(")").ToString();
并使用 that... 意思是:您不使用内联 SQL - 您使用完全参数化的 SQL。不过,ORM/微型 ORM 系列中的一些工具将极大地在这里提供帮助 - 使其成为单行工具。
关于c# - 使用 C# 将多个值传递给 SQL 内联查询中的单个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53217051/