通过C#转义SQL INSERT INTO中的特殊字符

fra*_*lly 6 c# sql sql-server escaping

我搜索过谷歌,但尚未找到任何解决方案.基本上我有一个在图库中设置的评论Feed(类似于facebook或stackoverflow评论).用户可以发表评论并阅读其他用户发布的评论.这工作正常.但是,如果用户尝试使用撇号发布评论,我会收到一个不错的小Web应用程序错误:

's'附近的语法不正确.字符串')'后面的未闭合引号.

我发布到SQL的评论是81.我想要一个能够逃脱所有特殊字符的解决方案,这样无论用户输入什么,无论什么,都不会出错.

代码背后

Fetcher.postUserComments(connectionString, imagePath, comments.ToString(), userId);
Run Code Online (Sandbox Code Playgroud)

提取程序

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

数据类型是字符串,我也试过做.ToString()但没有运气.提前感谢任何有用的输入.

Mik*_*son 10

您应该始终使用参数化查询.它们可以帮助您避免使用您所拥有的情况以及SQL注入攻击

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);
Run Code Online (Sandbox Code Playgroud)