在C#开发中,我们经常需要与Oracle数据库进行交互。传统的方法是安装Oracle客户端,并在代码中调用对应的Oracle库,但是这种方式往往会出现各种问题,如版本不兼容、安装失败等。那么,有没有一种不需要安装Oracle客户端就能访问Oracle数据库的方法呢?
答案是肯定的。下面介绍两种不需要安装Oracle客户端的方法:
1. 使用Oracle.ManagedDataAccess.Client
Oracle.ManagedDataAccess.Client是Oracle提供的一种用于.NET平台的数据访问组件,可以在不安装Oracle客户端的情况下直接连接Oracle数据库。使用方法和System.Data.SqlClient类似。
try
{
string connStr = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User ID=system;Password=123456;";
using (Oracle.ManagedDataAccess.Client.OracleConnection conn = new Oracle.ManagedDataAccess.Client.OracleConnection(connStr))
{
conn.Open();
Oracle.ManagedDataAccess.Client.OracleCommand cmd = new Oracle.ManagedDataAccess.Client.OracleCommand("select * from emp", conn);
Oracle.ManagedDataAccess.Client.OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr["empno"] + "," + dr["ename"] + "," + dr["job"] + "," + dr["mgr"] + "," + dr["hiredate"] + "," + dr["sal"] + "," + dr["comm"] + "," + dr["deptno"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
2. 使用ODP.NET Core
ODP.NET Core是 Oracle 官方提供的 .NET Standard 2.0(不需要安装.NET Framework或.NET Core )平台上对 Oracle 数据库进行数据访问的一种库。它是免费的、轻量级的,有大量的测试覆盖率,非常适合在 Linux、macOS 和 Windows 上构建高性能和可伸缩性服务。
try
{
string connStr = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL)));User ID=system;Password=123456;";
using (var connection = new Oracle.ManagedDataAccess.Client.OracleConnection(connStr))
{
connection.ConnectionString = connStr;
await connection.OpenAsync();
var command = connection.CreateCommand();
command.CommandText = "select * from emp";
await using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
Console.WriteLine(reader["empno"] + "," + reader["ename"] + "," + reader["job"] + "," + reader["mgr"] + "," + reader["hiredate"] + "," + reader["sal"] + "," + reader["comm"] + "," + reader["deptno"]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
综上所述,不安装Oracle客户端也可以实现与Oracle数据库进行数据交互。在使用过程中,需要注意版本兼容性。如果你还有其他好的方法,欢迎在评论区中分享。