解决C#连接informix数据库中文乱码

1. C#连接Informix

需要在windows主机安装informix csdk. 安装完成后在安装目录下面有.net连接informix的驱动, 大概位置如: C:\Program Files\IBM Informix Client-SDK\bin\netf40

 不同的版本的csdk可能会有不同的位置, 但大体和上面差不多,总之不好超出csdk的安装目录. 可以查找可用的dll文件: IBM.Data.Informix.dll , 这个文件就可以引入到C#项目的dll

把C:\Program Files\IBM Informix Client-SDK\bin目录加入到系统环境PATH中, 这个是C#连接informix的必要条件之一.

 

2. 建立安装C#项目

C#项目的具体建立这里不再赘述, 引入IBM.Data.Informix.dll 后,就可以进行测试连接,代码如下:

IfxConnection conn = new IfxConnection();
string cs = "Host=192.168.0.1;Service=9908;DataBase=mydb;Server=on_public;User ID=informix;Password=123456;Client_Locale=en_us.CP1252;DB_LOCALE=en_US.819";
conn.ConnectionString = cs;
conn.Open();

  

3.读取表数据

这里假设informix安装的时候使用默认的字符编码环境, 即en_US.819, iso-8859-1.

其实跟IfxConnection连接到informix使用的默认Client_Locale, DB_LOCALE是一样的.

读取数据的代码如下:

 1 IfxConnection connection = GetConnection();
 2 connection.Open();
 3 List<Hashtable> list = new List<Hashtable>();
 4 IfxCommand cmd = new IfxCommand(sql, connection);
 5 IfxDataReader reader = cmd.ExecuteReader();
 6 
 7 int count = reader.FieldCount;
 8 while (reader.Read())
 9 {
10     Hashtable row = new Hashtable();
11     for(int i = 0; i < count; i++)
12     {
13         string colname = reader.GetName(i);
14         object value;
15         if (reader.IsDBNull(i))
16         {
17             value = null;
18         }
19         else
20         {
21             value = reader.GetValue(i);
22             string type = value.GetType().Name.ToLower();
23             if (type.Contains("string"))
24             {
25                 //Encoding.Default.GetBytes(value.ToString());
26                 byte[] bytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(value.ToString());
27                 value = Encoding.Default.GetString(bytes);
28             }
29         }
30 
31         row[colname] = value;
32     }
33     list.Add(row);
34 }
35 
36 connection.Close();

因为C#连接informix读取的数据默认是读取ISO-8859-1数据编码, 中文在前台显示是乱码的,需要转换为C#默认的字符后才能正常显示.

相关代码如上面的代码的26行,27行.

 

4. 补充说明C#连接informix的参数, 除了以上代码列出来的参数之外, 再补充说明以下几个

参数说明
参数名 说明 默认值
Pooling When set to true, the IfxConnection object is drawn from the appropriate pool, or if necessary, it is created and added to the appropriate pool. true
Protocol, PRO The communication protocol used between the CreateConnection() and the database server.一般是留空,或者填onsoctcp, 主要是informix服务器配置对外连接的配置方式 ""
Max Pool Size The maximum number of connections allowed in the pool. 100
Min Pool Size The minimum number of connections allowed in the pool. 0
     
posted @ 2025-03-04 14:54  半岛拖鞋  阅读(53)  评论(0)    收藏  举报