C#-将变量添加到字符串中的特定点

本文关键字:字符串 变量 添加 C#- | 更新日期: 2023-09-27 18:25:31

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

例如:

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

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

一个可能的查询是"插入TABLEkey1key2)VALUES('value1','value2])"

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

C#-将变量添加到字符串中的特定点

您可以使用List存储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();

}