想在c#中访问oracle数据库,毕竟是开发,想要轻量级访问oracle,客户机上无需安装oracle环境就能正常运行程序。
在网上找了相关资料,只需要引用一个dll即可实现。
访问代码(需引用dll):
public class OracleConfig { //string connString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ip)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));Persist Security Info=True;User ID=system;Password=password;"; public string host { get; set; } public string port { get; set; } public string service { get; set; } public string id { get; set; } public string password { get; set; } }
public class OracleHelper { OracleConfig oracleConfig; OracleConnection oracleConnection; OracleDataReader oracleDataReader; OracleCommand oracleCommand; public OracleHelper(OracleConfig oracleConfig) { this.oracleConfig = oracleConfig; } public OracleDataReader GetDataReader(string commandText) { GetOracleConnection(oracleConfig); oracleCommand = oracleConnection.CreateCommand(); oracleCommand.CommandText = commandText; oracleDataReader = oracleCommand.ExecuteReader(); return oracleDataReader; } public void CloseConnection() { oracleDataReader.Close(); oracleDataReader.Dispose(); oracleCommand.Dispose(); oracleConnection.Close(); oracleConnection.Dispose(); } private void GetOracleConnection(OracleConfig oracleConfig) { oracleConnection = new OracleConnection(); oracleConnection.ConnectionString = string.Format("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));Persist Security Info=True;User ID={3};Password={4};", oracleConfig.host,oracleConfig.port,oracleConfig.service,oracleConfig.id,oracleConfig.password); oracleConnection.Open(); } }
OracleDataReader oracleDataReader = oracleHelper.GetDataReader("select * from table"); while (oracleDataReader.Read()) { Console.WriteLine(oracleDataReader["字段"].ToString()); } oracleHelper.CloseConnection();
dll下载地址:http://download.csdn.net/detail/lelehellow/9868148