The special use of single and double quotes in mysql and the common escape characters of mysql (turn)

The special use of single and double quotes in mysql and the common escape characters in mysql

mysql uses basic DML-type sql statements,  "" and ''  are default string label symbols. But in practice, the following situations often occur:

SELECT book_id FROM pd WHERE isbn='9787542739810' and book_name='"HBase实战"与"Storm实战"';

In this case, there is no problem with the string corresponding to book_name, and there is no syntax problem in the SQL statement. But look at the following statement:

SELECT book_id FROM pd WHERE isbn= '9787542739810'  and book_name= 'HBase enterprise application development practice' ;

Execute this statement:

报异常:You have an error in your SQL syntax;

At this point, everyone may say that you can replace the two single quotes in the 'HBase enterprise application development practice' with double quotes. But reality is often in the worst-case scenario according to Murphy's Law. In many cases, we do not know whether the incoming string of additions, deletions, changes, and checks contains ",', or both, so we can't simply replace single quotes with double quotes. Replace double quotes with single quotes. This requires the use of sql escape characters.

\ ‘

A single quote ("'") character.

\ ”

A double quote (" "") character.

\\

A backslash ("\") character.

The following is the java code for escaping, for reference only:

String str = "askdjf;lskdjf'asdf\"asdfasdf";
System.out.println(str);
if (str.indexOf("'") >= 0)
str = str.replaceAll("'", "\\\\'");
if (str.indexOf("\"") >= 0)
str = str.replaceAll("\"", "\\\\\"");
System.out.println(str);

mysql转义字符:

\0

一个ASCII 0 (NUL)字符。

\n

一个新行符。

\t

一个定位符。

\r

一个回车符。

\b

一个退格符。

\ ‘

一个单引号(“ ‘”)符。

\ ”

一个双引号(“ “”)符。

\\

一个反斜线(“\”)符。

\%

一个“%”符。它用于在正文中搜索“%”的文字实例,否则这里“%”将解释为一个通配符。

\_

一个“_”符。它用于在正文中搜索“_”的文字实例,否则这里“_”将解释为一个通配符。

注意,如果你在某些正文环境中使用“\%”或“\%_”,这些将返回字符串“\%”和“\_”而不是“%”和“_”。

有几种方法在一个字符串内包括引号:

一个字符串内用“ ‘”加引号的“ ‘”可以被写作为“ ‘ ‘”。

一个字符串内用“ “”加引号的“ “”可以被写作为“ ” “”。

你可以把一个转义字符(“\”)放在引号前面。

一个字符串内用“ “”加引号的“ ‘”不需要特殊对待而且不必被重复或转义。同理,一个字符串内用“ ‘”加引号的与“ “”也不需要特殊对待。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326684436&siteId=291194637