我是编码的新手,正在寻求有关如何在嵌入式SQL查询中将多个值传递给单个参数的帮助。我已经对以下查询进行了框架设计,但听说这可能会导致SQL注入问题。请帮助我如何通过使用基于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格式。
答案 0 :(得分:3)
如果您手动进行操作,则该过程(基本上)将是:
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 / micro-ORM系列中的工具在这里极大都可以提供帮助-使它成为一线工具。