Unicode (hexadecimal) character literals in MySQL

∥☆過路亽.° 提交于 2020-01-11 02:46:22

问题


Is there a way to specify Unicode character literals in MySQL?

I want to replace a Unicode character with an Ascii character, something like the following:

Update MyTbl Set MyFld = Replace(MyFld, "ẏ", "y")

But I'm using even more obscure characters which are not available in most fonts, so I want to be able to use Unicode character literals, something like

Update MyTbl Set MyFld = Replace(MyFld, "\u1e8f", "y")

This SQL statement is being invoked from a PHP script - the first form is not only unreadable, but it doesn't actually work!


回答1:


You can specify hexadecimal literals (or even binary literals) using 0x, x'', or X'':

select  0xC2A2;
select x'C2A2';
select X'C2A2';

But be aware that the return type is a binary string, so each and every byte is considered a character. You can verify this with char_length:

select char_length(0xC2A2)

2

If you want UTF-8 strings instead, you need to use convert:

select convert(0xC2A2 using utf8mb4)

And we can see that C2 A2 is considered 1 character in UTF-8:

select char_length(convert(0xC2A2 using utf8mb4))

1


Also, you don't have to worry about invalid bytes because convert will remove them automatically:

select char_length(convert(0xC1A2 using utf8mb4))

0

As can be seen, the output is 0 because C1 A2 is an invalid UTF-8 byte sequence.




回答2:


Thanks for your suggestions, but I think the problem was further back in the system.

There's a lot of levels to unpick, but as far as I can tell, (on this server at least) the command

set names utf8

makes the utf-8 handling work correctly, whereas

set character set utf8

doesn't.

In my environment, these are being called from PHP using PDO, for what difference that may make.

Thanks anyway!




回答3:


You can use the hex and unhex functions, e.g.:

update mytable set myfield = unhex(replace(hex(myfield),'C383','C3'))



回答4:


The MySQL string syntax is specified here, as you can see, there is no provision for numeric escape sequences.

However, as you are embedding the SQL in PHP, you can compute the right bytes in PHP. Make sure the bytes you put into the SQL actually match your client character set.




回答5:


There is also the char function that will allow what you wanted (providing byte numbers and a charset name) and getting a char.



来源:https://stackoverflow.com/questions/4256657/unicode-hexadecimal-character-literals-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!