Convert output of MySQL query to utf8

2020-02-16 08:04发布

问题:

I have a table in my database and I want run a query like

SELECT column1, column2 FROM my_table WHERE my_condition;

but I want the mysql to return the column2 in utf8 encoding. Is it any function in mysql to do such task? What is that?

回答1:

You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html

SELECT column1, CONVERT(column2 USING utf8)
FROM my_table 
WHERE my_condition;


回答2:

SELECT CONVERT(CAST(column as BINARY) USING utf8) as column FROM table 


回答3:

Addition:

When using the MySQL client library, then you should prevent a conversion back to your connection's default charset. (see mysql_set_character_set()[1])

In this case, use an additional cast to binary:

SELECT column1, CAST(CONVERT(column2 USING utf8) AS binary)
FROM my_table
WHERE my_condition;

Otherwise, the SELECT statement converts to utf-8, but your client library converts it back to a (potentially different) default connection charset.



标签: mysql sql utf-8