如何解决PostgreSQL命令行导出表时的编码转换错误?
问题描述
我在DBeaver中可通过以下COPY语句导出PostgreSQL表为CSV文件:
copy "Dibbs".macro to 'C:\Users\yuju\SQL_Data\PanelBidList.csv' with delimiter ',' csv header;
制作了批处理脚本执行相同操作,脚本内容如下:
psql -U postgres -p 5432 -h localhost -d postgres -a -f C:\Users\yuju\AppData\Roaming\DBeaverData\workspace6\General\Scripts\test.sql
通过DBeaver执行可生成正常的CSV文件,但使用批处理时出现错误:
ERROR: character with byte sequence 0xef 0xbf 0xbd in encoding "UTF8" has no equivalent in encoding "WIN1252"
请问解决该问题的最优方法是什么?
问题原因
DBeaver连接PostgreSQL时默认使用UTF8编码,与数据库编码匹配;而批处理中运行的psql默认继承Windows cmd的WIN1252编码,当数据库中存在WIN1252无法表示的UTF8字符时,转码就会失败报错。
解决方法
方法1:指定psql客户端为UTF8编码(最优)
在批处理的psql命令中添加编码参数,强制客户端使用UTF8编码,和数据库编码保持一致,彻底避免转码冲突:
psql -U postgres -p 5432 -h localhost -d postgres -E UTF8 -a -f C:\Users\yuju\AppData\Roaming\DBeaverData\workspace6\General\Scripts\test.sql
也可以通过设置环境变量实现:
set PGCLIENTENCODING=UTF8 psql -U postgres -p 5432 -h localhost -d postgres -a -f C:\Users\yuju\AppData\Roaming\DBeaverData\workspace6\General\Scripts\test.sql
方法2:在COPY语句中指定输出文件编码
修改COPY语句,明确指定CSV文件的编码为UTF8,让PostgreSQL直接输出UTF8格式文件,跳过客户端编码转码:
copy "Dibbs".macro to 'C:\Users\yuju\SQL_Data\PanelBidList.csv' with delimiter ',' csv header encoding 'UTF8';
方法3:切换批处理控制台编码
在批处理开头添加命令,将控制台编码切换为UTF8(适用于Windows 10及以上系统):
chcp 65001 psql -U postgres -p 5432 -h localhost -d postgres -a -f C:\Users\yuju\AppData\Roaming\DBeaverData\workspace6\General\Scripts\test.sql
注:此方法可能导致控制台显示乱码,但不影响最终CSV文件的生成。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

