2014-06-20 36 views
5

我已經搜索谷歌,還沒有找到任何解決方案,我的問題呢。基本上我有一個評論的飼料是在圖像庫中設置的(類似於Facebook或者stackoverflow評論)。用戶可以發表評論並閱讀其他用戶發表的評論。這工作正常。但是,如果用戶試圖發表評論與撇號,我得到一個不錯的web應用程序錯誤:在SQL INSERT INTO中通過C#逃脫特殊字符

Incorrect syntax near 's'. Unclosed quotation mark after the character string ')'.

說我張貼到SQL註釋是81的。我想要一個解決方案,將逃脫所有特殊字符,以便無論用戶輸入什麼,不管是什麼,都不會出錯。

代碼隱藏

Fetcher.postUserComments(connectionString, imagePath, comments.ToString(), userId); 

擷取

sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES ('" + userId + "', '" + imagePath + "', '" + comments + "', '" + theDate + "')"; 

的數據類型爲字符串,我也試着做了.ToString()但沒有運氣。預先感謝任何有用的意見。

+1

不要這樣做!您打開自己的[SQL注入攻擊](http://msdn.microsoft.com/en-us/library/ff648339.aspx)。更改您的代碼,以便參數化所有查詢。否則你會後悔的。 –

回答

7

你應該總是使用參數化querys。它們可以幫助您避免像您遇到的一個情況,以及SQL Injection attacks

sqlCom.CommandText = "INSERT INTO dbo.Table(userId, imagePath, userComments, dateCommented) VALUES (@userId, @imagePath, @userComments, @dateCommented)"; 

sqlCom.Parameters.AddWithValue("@userId", userId); 
sqlCom.Parameters.AddWithValue("@imagePath", imagePath); 
sqlCom.Parameters.AddWithValue("@userComments", comments); 
sqlCom.Parameters.AddWithValue("@dateCommented", theDate); 
+0

感謝您提供的信息和更正。現在一切正常。 –

3

你需要複製「文字註釋中

comments = comments.Replace("'", "''"); 

或者,更安全,是使用SQL參數,例如:

cmd.CommandText = "SELECT * FROM Client, Project WHERE Client.ClientName = @ClientName AND Project.ProjectName = @ProjectName"; 

cmd.Parameters.Add(new SqlParameter("@ClientName",client.SelectedValue)); 

cmd.Parameters.Add(new SqlParameter("@ProjectName",projnametxt.Text)); 
+0

這將是一個創可貼的解決方案。然後我必須爲所有特殊字符做到這一點。我正在尋找更持久的解決方案。不過謝謝你的建議。我需要更新的問題,以指出「所有特殊字符」 –

+0

***像***有特殊字符。也許可以逃脫。 – Kiquenet

3

你不應該這樣做...因爲它可以很容易SQL注入。我可以通過評論注入惡意SQL查詢,像...

;drop database master; 

使用的參數來避免SQL注入

command.Parameters.Add(new SqlParameter("@Param", value));