(ASP.NET)C#连接Oracle数据库示例(中文乱码问题解决)
接手了一个遗留的ASP.NET系统,数据库用的是Oracle,以前没搞过.NET和Oracle数据库,数据库搞了半天才解决乱码问题,在此做个笔记备忘。
1.下载安装ODAC
1)请去Oracle官网下载:http://www.oracle.com/technetwork/database/windows/downloads/index.html;
2)请下载对应版本和操作系统的
3)安装没有特殊要求
2.调整字符编码
1)查看Oracle数据库字符编码。
使用SQL语句查看(user是表名):
1 select userenv('language') from user;
结果示例:
IMPLIFIED CHINESE_CHINA.ZHS16GBKS
2)查看你ODAC字符编码
打开注册表regdit,查看hkey_local_machine\software\oracle\ 中nls_lang的值,如果和Oracle数据库编码:”IMPLIFIED CHINESE_CHINA.ZHS16GBKS“不一样,请修改为一样。
3.C#连接示例
注意:
- 引用:using System.Data.OleDb;
- OracleClient方式已经过时,所以采用OleDb;
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data.OleDb; 6 7 namespace OracleDBConnect 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 TestOracleConn(); 14 } 15 16 private static void TestOracleConn() 17 { 18 //数据库服务器IP,端口号,数据库名称,用户账号,用户密码 19 string ip = "202.203.33.76"; 20 string port = "1521"; 21 string dbName = "dbname"; 22 string userid = "admin"; 23 string password = "12345678"; 24 string conString = 25 "Provider=oraoledb.oracle;Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = " 26 + ip + ")(PORT = " + port + ")))(CONNECT_DATA =(SERVICE_NAME = " 27 + dbName + ")));User ID=" + userid + ";Password=" + password + ";"; 28 OleDbConnection conn = new OleDbConnection(conString); 29 conn.Open(); 30 31 OleDbCommand comm = new OleDbCommand("select * from T_USER", conn); 32 OleDbDataReader dr = comm.ExecuteReader(); 33 34 Console.WriteLine("用户名"); 35 while (dr.Read()) 36 { 37 string s = dr.GetString(1); 38 Console.WriteLine(s); 39 } 40 dr.Close(); 41 conn.Close(); 42 } 43 } 44 }