简体   繁体   English

应该在sql字符串参数中转义哪些字符

[英]what characters should be escaped in sql string parameters

I need a complete list of characters that should be escaped in sql string parameters to prevent exceptions. 我需要一个完整的字符列表,应该在sql字符串参数中进行转义以防止异常。 I assume that I need to replace all the offending characters with the escaped version before I pass it to my ObjectDataSource filter parameter. 我假设在将其传递给我的ObjectDataSource过滤器参数之前,我需要用转义版本替换所有违规字符。

No, the ObjectDataSource will handle all the escaping for you. 不,ObjectDataSource将为您处理所有转义。 Any parametrized query will also require no escaping. 任何参数化查询也不需要转义。

As others have pointed out, in 99% of the cases where someone thinks they need to ask this question, they are doing it wrong. 正如其他人所指出的,在有人认为他们需要提出这个问题的99%的案例中,他们做错了。 Parameterization is the way to go. 参数化是要走的路。 If you really need to escape yourself, try to find out if your DB access library offers a function for this (for example, MySQL has mysql_real_escape_string ). 如果你真的需要自己逃避,试着找出你的数据库访问库是否为此提供了一个函数(例如,MySQL有mysql_real_escape_string )。

Here's a way I used to get rid of apostrophes. 这是我用来摆脱撇号的一种方式。 You could do the same thing with other offending characters that you run into. 您可以与遇到的其他违规字符做同样的事情。 (example in VB.Net) (在VB.Net中的示例)

Dim companyFilter = Trim(Me.ddCompany.SelectedValue)

If (Me.ddCompany.SelectedIndex > 0) Then
      filterString += String.Format("LegalName like '{0}'", companyFilter.Replace("'", "''"))
End If

Me.objectDataSource.FilterExpression = filterString

Me.displayGrid.DataBind()

SQL Books online: Search for String Literals: SQL Books online:搜索字符串文字:

String Literals 字符串文字

A string literal consists of zero or more characters surrounded by quotation marks. 字符串文字由零个或多个由引号括起的字符组成。 If a string contains quotation marks, these must be escaped in order for the expression to parse. 如果字符串包含引号,则必须对这些引号进行转义,以便解析表达式。 Any two-byte character except \\x0000 is permitted in a string, because the \\x0000 character is the null terminator of a string. 字符串中允许除\\ x0000之外的任何双字节字符,因为\\ x0000字符是字符串的空终止符。

Strings can include other characters that require an escape sequence. 字符串可以包含需要转义序列的其他字符。 The following table lists escape sequences for string literals. 下表列出了字符串文字的转义序列。

\\a Alert \\ a警报

\\b Backspace \\ b退格

\\f Form feed \\ f表格Feed

\\n New line \\ n新行

\\r Carriage return \\ r \\ n回车

\\t Horizontal tab \\ t水平标签

\\v Vertical tab \\ v垂直选项卡

\\" Quotation mark “引号

\\ Backslash \\反斜杠

\\xhhhh Unicode character in hexadecimal notation \\ xhhhh十六进制表示法中的Unicode字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM