encoding指定导入文件的编码

最近更新时间: 2025-02-18 16:02:00

  • 复制
    复制成功
postgres=# \! enca -L zh_CN /data/pgxz/t.txt    
Simplified Chinese National Standard; GB2312
postgres=# copy t from '/data/pgxz/t.txt' ;
COPY 4
postgres=# select * from t;
 f1 |       f2       |             f3             | f4 
----+----------------+----------------------------+----
  1 | TDSQL PG          |                            |  7
  2 | pg'",      xc% | 2017-10-28 18:24:05.643102 |  3
  3 | pgxz           | 2017-10-28 18:24:05.645691 |   
  4 |                | 2017-10-30 16:41:09.157612 |  4
(4 rows)
#不指定导入文件的编码格式,则无法正确导入中文字符
postgres=# truncate table t;
TRUNCATE TABLE
postgres=# copy t from '/data/pgxz/t.txt' (encoding gbk) ;
COPY 4
postgres=# select * from t;
 f1 |       f2       |             f3             | f4 
----+----------------+----------------------------+----
  1 | TDSQL PG          |                            |  7
  2 | pg'",      xc% | 2017-10-28 18:24:05.643102 |  3
  3 | pgxz           | 2017-10-28 18:24:05.645691 |   
  4 | 腾讯           | 2017-10-30 16:41:09.157612 |  4
(4 rows)
#使用encoding gbk后便可以正确导入文件的内容,你也可以使用下面的方式转换导入文件的编码后再导入数据
postgres=# truncate table t;
TRUNCATE TABLE
postgres=# \! enconv -L zh_CN -x UTF-8 /data/pgxz/t.txt
postgres=# copy t from '/data/pgxz/t.txt';
COPY 4
postgres=# select * from t;
 f1 |       f2       |             f3             | f4 
----+----------------+----------------------------+----
  1 | TDSQL PG         |                            |  7
  2 | pg'",      xc% | 2017-10-28 18:24:05.643102 |  3
  3 | pgxz           | 2017-10-28 18:24:05.645691 |   
  4 | 腾讯           | 2017-10-30 16:41:09.157612 |  4
(4 rows)
postgres=#