天天看点

PostgreSQL字符集问题导致乱码

在使用PostgreSQL数据库,输入中文时,会遇到“ERROR:  invalid byte sequence for encoding "UTF8": 0xd6d0”的错误,原因是由于没有正确设置客户端字符集。

问题的原因:

默认情况下,PostgreSQL是不转换字符集的,如果你的数据库是UTF8的字符集,一般终端的中文字符集会设置为GBK,或en_US(查看终端的字符集可以看LANG环境变量的设置),所以你输入的中文是GBK的编码,这个编码不经转换的存入数据库中,而数据库是UTF8的,PostgreSQL一看没有这样的UTF8编码,所以当然报错了。

解决方法为:

方法一:设置postgresql的客户端编码为GBK,这时PostgreSQL就知道输入的内容是GBK编码的,这样PostgreSQL数据库会自动做字符集的转换,把其转换成UTF8编码。

方法二:直接设置终端的字符集编码为UTF8,让输入的编码直接为UTF8,而不是GBK。

看我具体的演示:

方法一:设置postgresql的客户端编码:

设置psql客户端字符集为GBK,方法有两种,一种是在psql中输入“\encoding GBK” ,另一种是设置环境变量“export PGCLIENTENCODING=GBK”,演示:

[postgres@cacti ~]$ psql -d testdb03

psql.bin (9.5.9)

Type "help" for help.

testdb03=# \l

testdb03=# select * from weather;

   city   | temp_lo | temp_hi | prcp |    date    

----------+---------+---------+------+------------

 China07  |      49 |      61 |    3 | 1994-12-17

testdb03=# INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('学校', '43', '10', '2.0', '1994-12-11');

INSERT 0 1

testdb03=# INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('大学', '43', '10', '2.0', '1994-12-11');

 学校     |      43 |      10 |    2 | 1994-12-11

 大学     |      43 |      10 |    2 | 1994-12-11

修改pgsql客户端字符集为GBK,再次查看表内容:

testdb03=# \encoding GBK

 У     |      43 |      10 |    2 | 1994-12-11

 ′    |      43 |      10 |    2 | 1994-12-11

(7 rows)

出现乱码,原因是psql数据库在初始化是指定的的字符集是utf8.

再次插入中文报错:

testdb03=# INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('小学', '43', '10', '2.0', '1994-12-11');

ERROR:  character with byte sequence 0xad 0xa6 in encoding "GBK" has no equivalent in encoding "UTF8"

切换psql客户端的字符集为utf8字符集再次插入不再报错了:

testdb03=# \encoding UTF8

 小学     |      43 |      10 |    2 | 1994-12-11

(8 rows)

testdb03=#

[postgres@cacti ~]$ export PGCLIENTENCODING=GBK

 У      |      43 |      10 |    2 | 1994-12-11

 ′      |      43 |      10 |    2 | 1994-12-11

 С      |      43 |      10 |    2 | 1994-12-11

 testdb03=# INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('小学', '43', '10', '2.0', '1994-12-11');

修改回源字符集UTF8

[postgres@cacti ~]$ export PGCLIENTENCODING=UTF8

[postgres@cacti ~]$ 

testdb03=# \d

            List of relations

 Schema |     Name     | Type  |  Owner   

--------+--------------+-------+----------

 public | postgres_log | table | postgres

 public | weather      | table | postgres

(2 rows)

方法二:设置终端的编码为UTF8:

[postgres@dsc ~]$ export LANG=zh_CN.UTF8

然后修改终端软件的字符集编码,我使用的是SecureCRT,修改方法为:

Option->Session Option->外观->字符编码,把那个下拉框的内容改成“UTF8”:

然后再插入数据测试:

[postgres@dsc ~]$ psql -d testdb03

psql (8.4.3)

testdb03=# select * from t;

 id |   name   

----+----------

  1 | 中国

  2 | 我的中国

testdb03=# insert into t values(3,'我的中国');

testdb03=# select * from t;                   

  3 | 我的中国

(3 rows)

 本文转自 wjw555 51CTO博客,原文链接:http://blog.51cto.com/wujianwei/1979023