C#-将变量添加到字符串中的特定点
我正试图在我正在开发的一个C#程序上建立一个MySQL连接。我已经到了构建查询的地步。我的基本前提是,在要调用的类中有一个函数,该函数接受表名和具有列名及其各自值的哈希表(对于insert命令) 例: 所以,我的问题是,我如何迭代Insert方法接收的哈希表,每次在特定的、不断变化的位置添加键和值 一个可能的查询是“插入表(键1、键2)的值('value1','value2')”C#-将变量添加到字符串中的特定点,c#,hashtable,C#,Hashtable,我正试图在我正在开发的一个C#程序上建立一个MySQL连接。我已经到了构建查询的地步。我的基本前提是,在要调用的类中有一个函数,该函数接受表名和具有列名及其各自值的哈希表(对于insert命令) 例: 所以,我的问题是,我如何迭代Insert方法接收的哈希表,每次在特定的、不断变化的位置添加键和值 一个可能的查询是“插入表(键1、键2)的值('value1','value2')” 我的难题是试图在字符串中找到匹配的键和值。您可以使用列表存储哈希表中的列名和值,然后将它们连接到命令文本中。该命令的
我的难题是试图在字符串中找到匹配的键和值。您可以使用列表存储哈希表中的列名和值,然后将它们连接到命令文本中。该命令的参数是在您遍历哈希表时添加的
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();
private void Insert(字符串tableName,哈希表hash)
{
MySqlCommand=newmysqlcommand();
List columnList=新列表();
列表值列表=新列表();
foreach(哈希中的DictionaryEntry条目)
{
Add(entry.Key.ToString());
valueList.Add(“@”+entry.Key.ToString());
command.Parameters.AddWithValue(“@”+entry.Key.ToString(),entry.Value);
}
command.CommandText=“插入“+tableName+”(“+string.Join(“,”,columnList.ToArray())+”)”;
command.CommandText+=“值(“+string.Join”(,”,valueList.ToArray())+”)”;
command.ExecuteScalar();
}您正在构建sql注入机。请使用参数。对于不是SQL的东西,请使用模板引擎。您不希望这样做。使用参数化查询,而不是从文本中构建查询。请检查此答案,以便继续。
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();