Program Club

MySQL에서 특수 문자를 어떻게 이스케이프합니까?

proclub 2020. 11. 6. 20:57
반응형

MySQL에서 특수 문자를 어떻게 이스케이프합니까?


예를 들면 :

select * from tablename where fields like "%string "hi"  %";

오류:

SQL 구문에 오류가 있습니다. MySQL 서버 버전에 해당하는 설명서에서 1 행의 'hi ""'근처에서 사용할 올바른 구문을 확인하십시오.

이 쿼리는 어떻게 작성합니까?


이 답변에 제공된 정보는 안전하지 않은 프로그래밍 관행으로 이어질 수 있습니다.

여기에 제공된 정보는 프로그램 버전, 데이터베이스 클라이언트 및 사용 된 문자 인코딩을 포함하여 (이에 국한되지 않음) MySQL 구성에 따라 크게 달라집니다.

보기 http://dev.mysql.com/doc/refman/5.0/en/string-literals.html를

MySQL은 다음 이스케이프 시퀀스를 인식합니다.
\ 0 ASCII NUL (0x00) 문자.
\ '작은 따옴표 ( "'") 문자.
\ "큰 따옴표 (" "") 문자.
\ b 백 스페이스 문자.
\ n 개행 (줄 바꿈) 문자.
\ r 캐리지 리턴 문자.
\ t 탭 문자.
\ Z ASCII 26 (Ctrl-Z). 표 다음의 참고를 참조하십시오.
\\ 백 슬래시 ( "\") 문자.
\ % "%"문자. 표 다음의 참고를 참조하십시오.
\ _ "_"문자. 표 다음의 참고를 참조하십시오.

그래서 당신은 필요합니다

select * from tablename where fields like "%string \"hi\" %";

로 비록 아래 빌 Karwin 노트 는 작은 따옴표를 사용하는 것이 좋습니다는, 그래서 문자열 구분 기호에 대한 따옴표를 사용하여, 표준 SQL이 아니다. 이것은 일을 단순화합니다.

select * from tablename where fields like '%string "hi" %';

나는 자바로 나만의 MySQL 이스케이프 방법을 개발했다.

아래 수업 코드를 참조하세요.

경고 : NO_BACKSLASH_ESCAPES SQL 모드가 활성화 된 경우 잘못되었습니다.

private static final HashMap<String,String> sqlTokens;
private static Pattern sqlTokenPattern;

static
{           
    //MySQL escape sequences: http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html
    String[][] search_regex_replacement = new String[][]
    {
                //search string     search regex        sql replacement regex
            {   "\u0000"    ,       "\\x00"     ,       "\\\\0"     },
            {   "'"         ,       "'"         ,       "\\\\'"     },
            {   "\""        ,       "\""        ,       "\\\\\""    },
            {   "\b"        ,       "\\x08"     ,       "\\\\b"     },
            {   "\n"        ,       "\\n"       ,       "\\\\n"     },
            {   "\r"        ,       "\\r"       ,       "\\\\r"     },
            {   "\t"        ,       "\\t"       ,       "\\\\t"     },
            {   "\u001A"    ,       "\\x1A"     ,       "\\\\Z"     },
            {   "\\"        ,       "\\\\"      ,       "\\\\\\\\"  }
    };

    sqlTokens = new HashMap<String,String>();
    String patternStr = "";
    for (String[] srr : search_regex_replacement)
    {
        sqlTokens.put(srr[0], srr[2]);
        patternStr += (patternStr.isEmpty() ? "" : "|") + srr[1];            
    }
    sqlTokenPattern = Pattern.compile('(' + patternStr + ')');
}


public static String escape(String s)
{
    Matcher matcher = sqlTokenPattern.matcher(s);
    StringBuffer sb = new StringBuffer();
    while(matcher.find())
    {
        matcher.appendReplacement(sb, sqlTokens.get(matcher.group(1)));
    }
    matcher.appendTail(sb);
    return sb.toString();
}

You should use single-quotes for string delimiters. The single-quote is the standard SQL string delimiter, and double-quotes are identifier delimiters (so you can use special words or characters in the names of tables or columns).

In MySQL, double-quotes work (nonstandardly) as a string delimiter by default (unless you set ANSI SQL mode). If you ever use another brand of SQL database, you'll benefit from getting into the habit of using quotes standardly.

Another handy benefit of using single-quotes is that the literal double-quote characters within your string don't need to be escaped:

select * from tablename where fields like '%string "hi" %';

MySQL has the string function QUOTE, and it should solve this problem:


You can use mysql_real_escape_string. mysql_real_escape_string() does not escape % and _, so you should escape MySQL wildcards (% and _) separately.


For strings like that, for me the most comfortable way to do it is doubling the ' or ", as explained in the MySQL manual:

There are several ways to include quote characters within a string:

A “'” inside a string quoted with “'” may be written as “''”.

A “"” inside a string quoted with “"” may be written as “""”.

Precede the quote character by an escape character (“\”).

A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a

Strings quoted with “'” need no special treatment.

It is from http://dev.mysql.com/doc/refman/5.0/en/string-literals.html.


If you're using a variable when searching in a string, mysql_real_escape_string() is good for you. Just my suggestion:

$char = "and way's 'hihi'";
$myvar = mysql_real_escape_string($char);

select * from tablename where fields like "%string $myvar  %";

For testing how to insert the double quotes in MySQL using the terminal, you can use the following way:

TableName(Name,DString) - > Schema
insert into TableName values("Name","My QQDoubleQuotedStringQQ")

After inserting the value you can update the value in the database with double quotes or single quotes:

update table TableName replace(Dstring, "QQ", "\"")

참고URL : https://stackoverflow.com/questions/881194/how-do-i-escape-special-characters-in-mysql

반응형