ADO.Net 将 SQL Server 提供程序中的所有字符串类型公开为 C# 字符串,这意味着它们已经转换为 Unicode。char(n)
对于像or之类的非 unicode 源列(显然是你的)varchar(n)
,ADO.Net SQL Server 提供程序使用源排序信息来确定编码。因此,如果您的非 unicode SQL Server 数据在 .Net 中以错误的编码表示,则它必须以错误的排序规则呈现给提供者。为您的数据选择适当的排序规则,SQL Server 的 ADO.Net 提供程序将使用适当的编码对其进行翻译。例如,如排序规则和代码页架构中所述,西里尔排序规则将导致代码页 1251,这很可能是您想要的。链接的文章包含解决问题所需的所有信息。
using System;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
public class Hello1
{
public static void Main()
{
try
{
using (SqlConnection conn = new SqlConnection("server=.;integrated security=true"))
{
conn.Open ();
// The .cs file must be saved as Unicode, obviously...
//
string s = "Работа в германии";
byte[] b = Encoding.GetEncoding(1251).GetBytes (s);
// Create a test table
//
SqlCommand cmd = new SqlCommand (
@"create table #t (
c1 varchar(100) collate Latin1_General_CI_AS,
c2 varchar(100) collate Cyrillic_General_CI_AS)",
conn);
cmd.ExecuteNonQuery ();
// Insert the same value twice, the original Unicode string
// encoded as CP1251
//
cmd = new SqlCommand (
@"insert into #t (c1, c2) values (@b, @b)", conn);
cmd.Parameters.AddWithValue("@b", b);
cmd.ExecuteNonQuery ();
// Read the value as Latin collation
//
cmd = new SqlCommand (
@"select c1 from #t", conn);
string def = (string) cmd.ExecuteScalar ();
// Read the same value as Cyrillic collation
//
cmd = new SqlCommand (
@"select c2 from #t", conn);
string cyr = (string) cmd.ExecuteScalar ();
// Cannot use Console.Write since the console is not Unicode
//
MessageBox.Show(String.Format(
@"Original: {0} Default collation: {1} Cyrillic collation: {2}",
s, def, cyr));
}
}
catch(Exception e)
{
Console.WriteLine (e);
}
}
}
结果是:
---------------------------
---------------------------
Original: Работа в германии Default collation: Ðàáîòà â ãåðìàíèè Cyrillic collation: Работа в германии
---------------------------
OK
---------------------------