2012-12-20 59 views
1

我需要通過C#將文本插入到MySQL表中。 dbConnect是我自己創建的適配器,而ProcessNonQuery只需要一個字符串。創建「安全」的MySQL字符串(轉義雙引號)

我無法插入包含字符"'的文字。

這是我的嘗試:

public void InsertArticle(string name, string title, string keywords, string desc, string content, int idCategory,bool featured)// int level, int typeArt 
{       
    this.dbConnect.ProcessNonQuery(" set global sql_mode=\"NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\""); 
    string strFeatured; 

    if (featured) 
     strFeatured = "1"; 
    else 
     strFeatured = "0"; 
    content = content.Replace("'", "\'"); 
    StringBuilder sbInsertArticle = new StringBuilder("INSERT INTO Article(NameArt, TitleArt, keywordsArt, DescArt, ContentArt, idCategory, idLevel, idTypeArt, Featured) VALUES('"); 
    sbInsertArticle.Append(name); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(title); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(keywords); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(desc); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(content); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(idCategory.ToString()); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(1); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(1); sbInsertArticle.Append("', '"); 
    sbInsertArticle.Append(strFeatured); sbInsertArticle.Append("')"); 

    string strInsertArticle = sbInsertArticle.ToString(); 
    this.dbConnect.ProcessNonQuery(strInsertArticle); 

} 
+3

使用佔位符/參數。那麼就沒有「那些人物」的問題。 [Bobby Tables]給出了簡單的例子(http://bobby-tables.com/csharp.html)。使用適當的ADO/.NET文檔給出了更多的例子。還有許多重複的「問題」。 – 2012-12-20 17:54:24

+0

嘗試http://stackoverflow.com/questions/6745393/how-to-add-like-special-characters-in-mysql-varchar-data-type-column – sajanyamaha

+2

有辦法做你需要使用轉義。但是,請聽@pst和_use參數化_。你會很高興你在路上...... – PinnyM

回答

1

有可能是沒有錯的連接器。發佈的代碼的輸出不會正確地轉義內容。

如果含量= it's don"t working然後輸出是這樣的:

INSERT INTO Article(NameArt, TitleArt, keywordsArt, 
    DescArt, ContentArt, idCategory, idLevel, idTypeArt, Featured) 
    VALUES('foo', 'bar', 'mysql escaping', 'hmph', 
    'it's don"t working', '12', '1', '1', '1'); 

這應該在任何連接器失效。

content = content.Replace("'", "\\'"); 

會是一個開始,但您至少應該使用類似mysql_real_escape_string()之類的東西。

編輯:進一步解釋

運行在一個測試程序下列行:

Console.WriteLine("'"); 
Console.WriteLine("\'"); 
Console.WriteLine("\\'"); 

前兩個將輸出'。最後會輸出\'

最後,這個問題不能在MySQL中解決,也不能在你的連接器中解決,因爲你選擇提供給調用者的接口。 void ProcessNonQuery(string strParam)太簡單了,不允許將「轉義」工作推送到API中所需的參數化查詢。因此,使用此「連接器」獲得的任何解決方案都將特定於您從(C#)調用它的語言,因爲轉到問題的數據庫或API層之前必須先解決轉義問題。許多人認爲這種糟糕的方法,這就是爲什麼他們推動你直接使用任何標準的MySQL連接器,而不是試圖將其中一個包裝在你自己的API中。

+0

謝謝。但我已經指定我不需要基於php的解決方案:只有Mysql解決方案或c#技巧! – Oumdaa

+0

這個C#解決方案不起作用! – Oumdaa

+0

@Oumdaa這行代碼不能按預期工作:'content = content.Replace(「'」,「\'」);'。這個答案的重點在於展示哪些可以解決這個問題。您的設置中肯定可能存在其他問題。 '「\'」'等同於'「'」'。 – 2013-01-02 14:17:20

相關問題