2013-07-30 48 views
0

我正在嘗試在我正在處理的C#程序上設置MySQL連接。我到了構建查詢的地步。我的基本前提是,你在一個你要調用的類中有一個函數,它接受一個表名和一個帶有列名和它們各自值(用於插入命令)的散列表。C# - 將變量添加到字符串中的特定點

例:

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

db.Insert(stories, hash); 

所以,我的問題是,如何我可以遍歷用插入法收到的哈希表,每次增加的關鍵和具體,變換位置值。

一個可能的查詢是 「INSERT INTO KEY1KEY2)VALUES( '值1', '值2')」

我的困境是試圖讓鍵和值匹配在字符串中。

+5

你正在建設一個SQL注入機。 –

+1

使用參數。對於不是SQL的東西,請使用模板引擎。 – SLaks

+1

你做**不**要做這個。使用參數化查詢,而不是從文本中構建它們 – Kevin

回答

0

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

}

相關問題