Ese*_*sen 0 c# postgresql utf-8
我正在使用PostgreSQL为C#桌面应用程序提供支持.当我使用PgAdmin查询分析器更新具有特殊字符的文本列(如版权商标)时,它可以很好地工作:
update table1 set column1='value with special character ©' where column2=1
Run Code Online (Sandbox Code Playgroud)
当我从我的C#应用程序使用相同的查询时,它会抛出一个错误:
用于编码的无效字节序列
在研究了这个问题之后,我理解.NET字符串使用UTF-16 Unicode编码.
考虑:
string sourcetext = "value with special character ©";
// Convert a string to utf-8 bytes.
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(sourcetext);
// Convert utf-8 bytes to a string.
string desttext = System.Text.Encoding.UTF8.GetString(utf8Bytes);
Run Code Online (Sandbox Code Playgroud)
这里的问题是sourcetext和desttext编码为UTF-16字符串.当我通过时desttext,我仍然得到例外.
我也试过以下没有成功:
Encoder.GetString, BitConverter.GetString
Run Code Online (Sandbox Code Playgroud)
编辑:我甚至试过这个并没有帮助:
unsafe
{
String utfeightstring = null;
string sourcetext = "value with special character ©";
Console.WriteLine(sourcetext);
// Convert a string to utf-8 bytes.
sbyte[] utf8Chars = (sbyte[]) (Array) System.Text.Encoding.UTF8.GetBytes(sourcetext);
UTF8Encoding encoding = new UTF8Encoding(true, true);
// Instruct the Garbage Collector not to move the memory
fixed (sbyte* pUtf8Chars = utf8Chars)
{
utfeightstring = new String(pUtf8Chars, 0, utf8Chars.Length, encoding);
}
Console.WriteLine("The UTF8 String is " + utfeightstring);
}
Run Code Online (Sandbox Code Playgroud)
.NET中是否支持存储UTF-8编码字符串的数据类型?有没有其他方法来处理这种情况?
根据单项目PostgreSQL中的这个页面,他们建议如果你有UTF8字符串的错误,你可以在连接字符串中设置编码为unicode(如果你使用的是Npgsql驱动程序):
编码:要使用的编码.可能的值:ASCII(默认)和UNICODE.如果您遇到UTF-8值问题,请使用UNICODE:Encoding = UNICODE
我一直在寻找官方的Npgsql文档,它没有被提及. NpgsqlConnection.ConnectionString
| 归档时间: |
|
| 查看次数: |
3148 次 |
| 最近记录: |