【问题标题】:C# - Add variables to specific points in a stringC# - 将变量添加到字符串中的特定点
【发布时间】:2013-07-30 23:16:01
【问题描述】:

我正在尝试在我正在处理的 C# 程序上建立 MySQL 连接。我已经到了构建查询的地步。我的基本前提是你在一个你要调用的类中有一个函数,它接受一个表的名称和一个带有列名及其各自值的哈希表(用于插入命令)。

例如:

Hashtable hash = new Hashtable();
hash.Add("title", title);
hash.Add("contents", content);

db.Insert(stories, hash);

所以,我的问题是,我如何遍历 Insert 方法接收的哈希表,每次都在特定的变化位置添加键和值。

可能的查询是“插入到 TABLE (key1, key2) VALUES ('value1' , 'value2')"

我的困境是试图让键和值在字符串中匹配。

【问题讨论】:

  • 你正在构建一个 sql 注入机器。
  • 使用参数。对于不是 SQL 的东西,请使用模板引擎。
  • 你确实想要这样做。使用参数化查询而不是从文本构建它们
  • 查看此 SO 答案以帮助您前进。 stackoverflow.com/a/652999/2270839

标签: c# hashtable


【解决方案1】:

您可以使用 List 来存储 Hashtable 中的列名和值,然后将它们连接到命令文本中。该命令的参数是在您遍历 Hashtable 时添加的。

private void Insert(string tableName, Hashtable hash)
{
    MySqlCommand command = new MySqlCommand();

    List<string> columnList = new List<string>();
    List<string> valueList = new List<string>();

    foreach (DictionaryEntry entry in hash)
    {
        columnList.Add(entry.Key.ToString());
        valueList.Add("@" + entry.Key.ToString());

        command.Parameters.AddWithValue("@" + entry.Key.ToString(), entry.Value);
    }

    command.CommandText = "INSERT INTO " + tableName + "(" + string.Join(", ", columnList.ToArray()) + ") ";
    command.CommandText += "VALUES (" + string.Join(", ", valueList.ToArray()) + ")";

    command.ExecuteScalar();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2017-04-03
    • 2021-12-21
    • 1970-01-01
    • 2023-04-10
    • 2023-03-12
    • 2015-11-14
    相关资源
    最近更新 更多