You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Npgsql从PostgreSQL 12读取character varying字段数据异常求助

PostgreSQL character varying字段读取乱码问题解决建议

问题描述

使用C#程序通过Npgsql读取PostgreSQL 12数据库的character varying字段时,存储值如"Stanley Kubrick",读取后变量值为"1\0\0\0\u00042\0\0\0\u0004T\0\0\0p",已尝试修改编解码、更新Npgsql DLL,问题仍存在。

原代码示例

NpgsqlDataSource DataSource = NpgsqlDataSource.Create(connectionString);
NpgsqlCommand command = DataSource.CreateCommand("SET client_encoding = 'UTF8'");
command.ExecuteNonQuery();

command = DataSource.CreateCommand(this.Config.PostgreSQL_CommandString);
int righe= command.ExecuteNonQuery();
NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    var v = reader.GetValue(1);
}

解决建议

  • 移除错误的ExecuteNonQuery调用:对于SELECT查询,ExecuteNonQuery()会提前执行命令并返回受影响行数,导致后续ExecuteReader()读取的数据异常。直接删除这行代码,跳过不必要的执行步骤。
  • 使用类型安全的读取方法:避免使用GetValue()返回object类型,针对character varying字段,直接调用reader.GetString(1)读取字符串,Npgsql会自动处理编码转换,确保拿到可读文本。
  • 简化编码配置:Npgsql默认使用UTF-8编码,无需手动执行SET client_encoding = 'UTF8',可在连接字符串中显式指定编码确保生效,示例:
    Server=你的服务器;Port=5432;Database=你的库;User Id=账号;Password=密码;Client Encoding=UTF8
    
  • 验证字段类型匹配:检查数据库中目标字段是否确实为character varying(或varchar),若字段是二进制类型(如bytea),读取后会得到字节数组,转成字符串会出现乱码。可通过reader.GetFieldType(1)查看字段类型,确认与预期一致。

修改后的示例代码

var connectionString = "你的连接字符串(包含Client Encoding=UTF8)";
NpgsqlDataSource dataSource = NpgsqlDataSource.Create(connectionString);

using NpgsqlCommand command = dataSource.CreateCommand(this.Config.PostgreSQL_CommandString);
using NpgsqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
    string value = reader.GetString(1);
    // 处理读取到的字符串
}

内容的提问来源于stack exchange,提问作者Claudio Venturoli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 06:32:09