SQL字符串中的单引号处理

我有一个应用程序,其中文本字段中的值被发送到数据库。

例如,我有一个带有一个字段的表单(文本框)。 当我按下Ok按钮时,文本字段的内容将作为记录插入到表中。 我只是修剪文本框的文本并将其解压缩为变量并将其传递给我的SQL字符串。

问题在于,无论什么类似“It’s”或“Friend’s”这样的单引号都被识别为字符串的结尾。 在Delphi中,我见过像QuotedString这样的QuotedString来避免这种情况。 你的任何想法?

不要像这样构建SQL语句,它非常不安全(阅读本文) 。 使用参数,即:

 var command = new SqlCommand("select * from person where firstname = @firstname"); SqlParameter param = new SqlParameter(); param.ParameterName = "@firstname"; param.Value = "testing12'3"; command.Parameters.Add(param); 

使用.Replace("'","''''")

例如

 string name = txtName.Text.Replace("'","''''"); 

现在name可以作为存储过程中的参数等传递。

希望对你有帮助 …

 public static string DoQuotes(string sql) { if (sql == null) return ""; else return sql.Replace("'", "''"); }