I’m having a really hard time figuring out how to replace a special character with another in SQL (MySQL syntax). I’ve already tried with REPLACE function without success. What I would like to do is:
From this string:
"C:foobarfile.txt"
Obtain this string:
"C:\foo\bar\file.txt"
2
As I thought – this is an XY problem. MySQL does not require anything from the path. What it does require though is its input to be syntactical. In input, the string literal interprets the sequences of backslash and another character as “escape”, which removes special meaning from the next character. Since backslash is such a special character, it can be escaped to remove its special significance: one writes \
to get a string with a single backslash.
What this means is, if you write 'C:\foo\bar\file.txt'
in an SQL command, MySQL will understand it as the string 'C:foobarfile.txt'
(like in my comment under your question). If you write 'C:foobarfile.txt'
, MySQL will understand the backslash as removing the special significance from letters f
, b
and f
(not that they had any in the first place), and the string it will end up with will be 'C:foobarfile.txt'
.
Once the string is inside MySQL, it is correct, no replacements are necessary. Thus, you cannot use MySQL’s REPLACE
to prepare the string for input to MySQL – it is way too late for this. It is kind of like punching the baby in the stomach to pre-chew its food after it has already eaten it, it doesn’t work that way and it hurts the baby.
Rather than that, use the language that you use to interface with the database (you didn’t tag it, so I can’t give you the details) to properly handle the strings. Many languages have functions that will correctly escape strings for you for use by MySQL. Even better, learn about prepared statements and parametrised queries, which completely remove the need for explicit escaping.
The best reference on parametrised queries I can recommend, with remedies for multiple languages, is the Bobby Tables site.
4
REPLACE function should do the job for you – https://dev.mysql.com/doc/refman/8.0/en/replace.html.
How are you passing the string into REPLACE function?
5