There is another way to do this, which may or may not be safer, depending on your point of view. This requires MySQL 5.6 or later due to the use of a specific string function: FROM_BASE64 .
Suppose you have this message that you want to insert:
βAh,β the almost headless Nick waved an elegant hand, βthe question is unimportant ... Not that I really wanted to join ... I think I would have applied, but obviously I'm not fulfilling the requirements.β
This quote has a bunch of single- and double quotes, and it would be very difficult to insert it into MySQL. If you paste this from a program, quotes, etc. are easily avoided. But, if you need to paste this into an SQL script, you will have to edit the text (to avoid quotes), which can lead to errors. or sensitive to word wrap, etc.
Instead, you can encode Base64 text so that you have a βcleanβ line:
JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K
Some notes on Base64 encoding:
- Base64 encoding is a binary encoding, so you better make sure that you correctly specify your character set when encoding, because MySQL is going to decode the encoded Base64 string into bytes, and then interpret them. Make sure
base64 and MySQL agree on character encoding (I recommend UTF-8). - I wrapped a row in 50 columns for readability when stack overflows. You can wrap it in any number of columns that you want (or not wrap at all), and it will still work.
Now, to load this into MySQL:
SWtGb0xDSWdUbVZoY214NUlFaGxZV1JzWlhOeklFNXBZMnNnZD JGMlpXUWdZVzRnWld4bFoyRnVkQ0JvWVc1a0xDQWlZU0J0WVhS MFpYCklnYjJZZ2JtOGdhVzF3YjNKMFlXNWpaUzRnTGlBdUlDNG dTWFFuY3lCdWIzUWdZWE1nZEdodmRXZG9JRWtnY21WaGJHeDVJ SGRoYm5SbApaQ0IwYnlCcWIybHVMaUF1SUM0Z0xpQlVhRzkxWj JoMElFa25aQ0JoY0hCc2VTd2dZblYwSUdGd2NHRnlaVzUwYkhr Z1NTQW5aRzl1SjMKUWdablZzWm1sc2JDQnlaWEYxYVhKbGJXVn VkSE1uSUMwaUlBPT0K '));
This will insert without any complaints, and you did not need to manually escape the text inside the line.
Christopher Schultz Feb 16 '17 at 20:18 2017-02-16 20:18
source share