Escape special characters in SQL INSERT INTO via C#

本小妞迷上赌 提交于 2019-12-23 09:17:36

问题


I have searched google and haven't found any solution for my issue yet. Basically I have a comments feed that is setup within an image gallery (similar to facebook or stackoverflow comments). Users can post comments and read comments posted by other users. This is working fine. However, if a user tries to post a comment with an apostrophe, I get a nice little web application error:

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

The comment that I'm posting to SQL is 81's. I'm wanting a solution that will escape all special characters so that whatever the user types in, no matter what, doesn't error out.

Code Behind

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

Fetcher

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

The data type is string and I've also tried doing a .ToString() but no luck. Thanks in advance for any helpful input.


回答1:


You should always use parameterized querys. They help you avoid situations like the one you are having, as well as 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);



回答2:


You need to duplicate the ' character in comments

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

Alternatively, but more safety, is to use Sql parameter, example :

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));



回答3:


You should NEVER do this...because it allows for easy SQL injection. I could inject malicious sql queries through a comment, something like...

 ;drop database master;

use parameters instead to avoid sql injection

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


来源:https://stackoverflow.com/questions/24319597/escape-special-characters-in-sql-insert-into-via-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!