c# - 使用 C# 将多个值传递给 SQL 内联查询中的单个参数

标签 c# sql bulkinsert

我是编码新手,正在寻找有关如何将多个值传递给内联 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/

相关文章:

c# - 如何检查 NotifyIcon 是否被隐藏

sql - PostgreSQL 上一个和下一个组值

MYSQL批量INSERT慢

java - 如何通过Java在MongoDB中一次插入多个文档

sql-server - SQL Server 2005批量插入二进制类型

c# - 如何在 UWP 中将 Windows.UI.Xaml.Controls.DatePicker 格式化为 dd-MM-yyyy?

c# - 如何批量循环遍历IEnumerable

c# - AppBar 焦点问题

mysql - 在同一查询中更新列两次

java - 简单 SQL 正则表达式的问题