mysql: replace \ (backslash) in strings

前端 未结 6 800
执念已碎
执念已碎 2021-01-04 11:37

I am having the following problem:

I have a table T which has a column Name with names. The names have the following structure:

A\\\\B\\C

You can cre

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 12:00

    You're confusing what's IN the database with how you represent that data in SQL statements. When a string in the database contains a special character like \, you have to type \\ to represent that character, because \ is a special character in SQL syntax. You have to do this in INSERT statements, but you also have to do it in the parameters to the REPLACE function. There are never actually any double slashes in the data, they're just part of the UI.

    Why do you think you need to double the slashes in the SQL expression? If you're typing queries, you should just double the slashes in your command line. If you're generating the query in a programming language, the best solution is to use prepared statements; the API will take care of proper encoding (prepared statements usually use a binary interface, which deals with the raw data). If, for some reason, you need to perform queries by constructing strings, the language should hopefully provide a function to escape the string. For instance, in PHP you would use mysqli_real_escape_string.

    But you can't do it by SQL itself -- if you try to feed the non-escaped string to SQL, data is lost and it can't reconstruct it.

提交回复
热议问题