How do I set encoding in an NpgsqlConnection

爷,独闯天下 提交于 2019-12-11 06:08:02

问题


I have a PostgreSQL database, which uses character encoding WIN1252.

When querying the database, some records will produce an error when trying to read the data, because it is trying to convert it to UTF8. This happens on some foreign names containing certain non-Latin characters.

The error is:

ERROR: 22P05: character with byte sequence 0x81 in encoding "WIN1252" has no equivalent in encoding "UTF8"

It happens when I call Read() on the NpgsqlDataReader.

My connection is defined as:

new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=xyz;User Id=****;Password=****;");

What can I do to read this data using C#?


回答1:


I've managed to solve the problem. There is no way of setting the property in the connection string or any of the properties of the NpgsqlConnection or NpgsqlCommand.

However, I was able to set the value of client_encoding in a query. So directly after opening the connection I first executed the (non)query:

set client_encoding = 'WIN1252'

After that, any subsequent command on the same connection used the proper encoding and returned the results without complaints.



来源:https://stackoverflow.com/questions/16342198/how-do-i-set-encoding-in-an-npgsqlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!