(转) C#使用ODP.NET(Oracle.ManagedDataAccess.dll)操作Oracle数据库
原贴链接:https://www.cnblogs.com/mq0036/p/11052359.html
C#使用ODP.NET(Oracle.ManagedDataAccess.dll)操作Oracle数据库
在刚接触C#的时候由于公司使用的就是Oracle数据库,那么C#怎么连接Oracle数据库就成了首要去掌握的知识点了。在那时没有ODP.NET,但visual studio却对Oralce数据库的调用进行了集成,就是下图中的这个,尽管现在使用这个的时候visual studio提醒过时的,但在那时却是非常好用的。
为什么现在visual studio中这个程序集依然能使用,有ODP.NET,单单要拿出Oracle.ManagedDataAccess.dll进行本文的重点呢?
1、visual studio中提醒过时,因为微软和甲骨文存在数据库的竞争关系,并且从.NET的更新来看这个程序集没有再更新过,对于数据库一直在更新而调用的程序集一直不更新敢用下去么?还有一个我认为非常重要的原因就是使用这个程序集,摆脱不了每一个运行程序的客户机上都要去安装Oracle客户端的事实,试想一下,如果用户数量巨大的时候,安装客户端的工作量就相当的大,很耗费资源;
2、甲骨文后来出了ODP.NET,各种资料以及官网上都说需要安装ODP.NET,然后引用Oracle.ManagedDataAccess.dll,他和visual studio中的程序集最大的区别在于会随着数据库更新,是oracle官方出的驱动;
3、其实经过测试,ODP.NET的安装完全是没有必要的,直接在网上下载一个Oracle.ManagedDataAccess.dll,按如下方式引用即可,使用此种方式减少了ODP.NET的安装,无视操作系统的位数,最重要的是减少了Oracle客户端的安装;
那在哪里下载Oracle.ManagedDataAccess.dll呢?如果Oracle.ManagedDataAccess.dll有更新怎么知道呢?这个时候全宇宙最强大开发工具登场了!
安装完成就可以撸代码了,并且如果有更新可以随时能看到。并且在编程方面和以前使用System.Data.OracleClient程序集没有多大的不同,基本上拿以前使用System.Data.OracleClient程序集的代码做少许的改动即可。
1、使用了连接字符串,而不是用oracle客户端的服务名了;
2、几个命名空间的变化;
下面是对数据库常用操作的封装
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using Oracle.ManagedDataAccess.Client; using System.Data; using System.IO; using System.Collections; using System.Diagnostics; using Oracle.ManagedDataAccess.Types; namespace OracleDemo { public class OracleHelper { private static string connStr = "User Id=admin;Password=123;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.0.1)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=test)))"; #region 执行SQL语句,返回受影响行数 public static int ExecuteNonQuery(string sql, params OracleParameter[] parameters) { using (OracleConnection conn = new OracleConnection(connStr)) { conn.Open(); using (OracleCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } } #endregion #region 执行SQL语句,返回DataTable;只用来执行查询结果比较少的情况 public static DataTable ExecuteDataTable(string sql, params OracleParameter[] parameters) { using (OracleConnection conn = new OracleConnection(connStr)) { conn.Open(); using (OracleCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); OracleDataAdapter adapter = new OracleDataAdapter(cmd); DataTable datatable = new DataTable(); adapter.Fill(datatable); return datatable; } } } #endregion } }
以下代码是调用部分
string sqlString = "Select a.col1,a.col2 From test a Where a.id=:id"; DataTable dt = OracleHelper.ExecuteDataTable(sqlString,new OracleParameter(":id",1));
程序编写完成,生成完成后,目录大概如下:
这时候拷贝Debug文件夹到目标客户电脑上即可直接运行了(前提是目标客户电脑上有.NET Framework),完全摆脱安装Oracle客户端。
出处:https://www.cnblogs.com/goldenbridge/p/7812081.html
===========================================================
一、学习背景:
1)微软自vs2010后放弃了自家的system.data.oracleClient驱动,推荐使用oracle提供的驱动。
2)微软提供的system.data.oracleClient驱动存在oracle32位与64位连接兼容性的问题,解决起来费时费力。
二、Oracle推荐的驱动:oracle.DataAccess.dll与oracle.ManagedDataAccess.dll
1)oracle.DataAccess.dll的缺陷。oracle.DataAccess.dll需要几个dll文件,在实际使用中发现,oracle.DataAccess.dll无客户端连接方式同样存在所使用的dll文件的32位与64位和oracle数据库或系统本身存在的dll存在连接兼容性问题。所以不推荐使用该驱动。
2)推荐使用oracle.ManagedDataAccess.dll(oracle.ManagedDataAccess.Client)全托管驱动。实际使用发现,oracle全托管驱动对32位和64位oracle数据库具有很好的连接兼容性。可采用无客户端远程连接oracle,或在本机使用连接。可通过visual studio 2010 nuget安装,或直接下载dll文件,然后引用oracle.ManagedDataAccess.dll文件。在项目数据访问层中引用命名空间using oracle.ManagedDataAccess.Client,如图2-1
图 2-1引用oracle.ManagedDataAccess.Client命名空间
三、Web.config连接字符串
NET提供的链接字符串connectionString="DataSource=192.168.1.2:1521/orcl;Persist Security Info=True;User ID=scott;Password=tiger";
四、关于command.BindByName = true;(重点敲黑板)
1)在使用全托管驱动oracle.ManagedDataAccess.dll后,ado.net的增删查语句都执行正常,但是在执行修改语句(update语句)时,会引发异常。
2)默认情况下ODP.Net 绑定变量时,sql语句中的变量顺序必须和变量绑定顺序一致,否则Fill查不到数据,cmd.ExecuteNonQuery()返回0无法执行,将BindByName 设为true后,sql变量顺序和绑定顺序即可不一致
出处:https://blog.csdn.net/windows_xp_guule/article/details/80565243
===========================================================
基于C#语言Oracle.ManagedDataAccess操作Oracle数据库连接语句
Oracle.ManagedDataAccess下载地址: https://download.csdn.net/download/u012949335/10643367
using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Configuration; using Oracle.ManagedDataAccess; using Oracle.ManagedDataAccess.Types; using Oracle.ManagedDataAccess.Client; namespace DB { /// <summary> /// 数据访问基础类(基于Oracle) Copyright (C) Maticsoft /// 可以用户可以修改满足自己项目的需要。 /// </summary> public abstract class DbHelperOra { //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. public static string connectionString = PubConstant.ConnectionString; public DbHelperOra() { } #region 公用方法 public static int GetMaxID(string FieldName, string TableName) { string strsql = "select max(" + FieldName + ")+1 from " + TableName; object obj = GetSingle(strsql); if (obj == null) { return 1; } else { return int.Parse(obj.ToString()); } } public static bool Exists(string strSql) { object obj = GetSingle(strSql); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } public static bool Exists(string strSql, params OracleParameter[] cmdParms) { object obj = GetSingle(strSql, cmdParms); int cmdresult; if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) { cmdresult = 0; } else { cmdresult = int.Parse(obj.ToString()); } if (cmdresult == 0) { return false; } else { return true; } } #endregion #region 执行简单SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand cmd = new OracleCommand(SQLString,connection)) { try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(OracleException E) { connection.Close(); throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">多条SQL语句</param> public static void ExecuteSqlTran(ArrayList SQLStringList) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection=conn; OracleTransaction tx=conn.BeginTransaction(); cmd.Transaction=tx; try { for(int n=0;n<SQLStringList.Count;n++) { string strsql=SQLStringList[n].ToString(); if (strsql.Trim().Length>1) { cmd.CommandText=strsql; cmd.ExecuteNonQuery(); } } tx.Commit(); } catch(OracleException E) { tx.Rollback(); throw new Exception(E.Message); } } } /// <summary> /// 执行带一个存储过程参数的的SQL语句。 /// </summary> /// <param name="SQLString">SQL语句</param> /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString,string content) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(SQLString,connection); OracleParameter myParameter = new OracleParameter("@content", OracleDbType.Varchar2); myParameter.Value = content ; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(OracleException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) /// </summary> /// <param name="strSQL">SQL语句</param> /// <param name="fs">图像字节,数据库的字段类型为image的情况</param> /// <returns>影响的记录数</returns> public static int ExecuteSqlInsertImg(string strSQL,byte[] fs) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(strSQL,connection); OracleParameter myParameter = new OracleParameter("@fs", OracleDbType.LongRaw); myParameter.Value = fs ; cmd.Parameters.Add(myParameter); try { connection.Open(); int rows=cmd.ExecuteNonQuery(); return rows; } catch(OracleException E) { throw new Exception(E.Message); } finally { cmd.Dispose(); connection.Close(); } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { using(OracleCommand cmd = new OracleCommand(SQLString,connection)) { try { connection.Open(); object obj = cmd.ExecuteScalar(); if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } catch(OracleException e) { connection.Close(); throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ExecuteReader(string strSQL) { OracleConnection connection = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand(strSQL,connection); try { connection.Open(); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); return myReader; } catch(OracleException e) { throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString) { using (OracleConnection connection = new OracleConnection(connectionString)) { DataSet ds = new DataSet(); try { connection.Open(); OracleDataAdapter command = new OracleDataAdapter(SQLString,connection); command.Fill(ds,"ds"); } catch(OracleException ex) { throw new Exception(ex.Message); } return ds; } } #endregion #region 执行带参数的SQL语句 /// <summary> /// 执行SQL语句,返回影响的记录数 /// </summary> /// <param name="SQLString">SQL语句</param> /// <returns>影响的记录数</returns> public static int ExecuteSql(string SQLString,params OracleParameter[] cmdParms) { using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand cmd = new OracleCommand()) { try { PrepareCommand(cmd, connection, null,SQLString, cmdParms); int rows=cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return rows; } catch(OracleException E) { throw new Exception(E.Message); } } } } /// <summary> /// 执行多条SQL语句,实现数据库事务。 /// </summary> /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的OracleParameter[])</param> public static void ExecuteSqlTran(Hashtable SQLStringList) { using (OracleConnection conn = new OracleConnection(connectionString)) { conn.Open(); using (OracleTransaction trans = conn.BeginTransaction()) { OracleCommand cmd = new OracleCommand(); try { //循环 foreach (DictionaryEntry myDE in SQLStringList) { string cmdText=myDE.Key.ToString(); OracleParameter[] cmdParms=(OracleParameter[])myDE.Value; PrepareCommand(cmd,conn,trans,cmdText, cmdParms); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); trans.Commit(); } } catch { trans.Rollback(); throw; } } } } /// <summary> /// 执行一条计算查询结果语句,返回查询结果(object)。 /// </summary> /// <param name="SQLString">计算查询结果语句</param> /// <returns>查询结果(object)</returns> public static object GetSingle(string SQLString,params OracleParameter[] cmdParms) { using (OracleConnection connection = new OracleConnection(connectionString)) { using (OracleCommand cmd = new OracleCommand()) { try { PrepareCommand(cmd, connection, null,SQLString, cmdParms); object obj = cmd.ExecuteScalar(); cmd.Parameters.Clear(); if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value))) { return null; } else { return obj; } } catch(OracleException e) { throw new Exception(e.Message); } } } } /// <summary> /// 执行查询语句,返回OracleDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="strSQL">查询语句</param> /// <returns>OracleDataReader</returns> public static OracleDataReader ExecuteReader(string SQLString,params OracleParameter[] cmdParms) { OracleConnection connection = new OracleConnection(connectionString); OracleCommand cmd = new OracleCommand(); try { PrepareCommand(cmd, connection, null,SQLString, cmdParms); OracleDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return myReader; } catch(OracleException e) { throw new Exception(e.Message); } } /// <summary> /// 执行查询语句,返回DataSet /// </summary> /// <param name="SQLString">查询语句</param> /// <returns>DataSet</returns> public static DataSet Query(string SQLString,params OracleParameter[] cmdParms) { using (OracleConnection connection = new OracleConnection(connectionString)) { OracleCommand cmd = new OracleCommand(); PrepareCommand(cmd, connection, null,SQLString, cmdParms); using( OracleDataAdapter da = new OracleDataAdapter(cmd) ) { DataSet ds = new DataSet(); try { da.Fill(ds,"ds"); cmd.Parameters.Clear(); } catch(OracleException ex) { throw new Exception(ex.Message); } return ds; } } } private static void PrepareCommand(OracleCommand cmd,OracleConnection conn,OracleTransaction trans, string cmdText, OracleParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = CommandType.Text;//cmdType; if (cmdParms != null) { foreach (OracleParameter parm in cmdParms) cmd.Parameters.Add(parm); } } #endregion #region 存储过程操作 /// <summary> /// 执行存储过程 返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleDataReader</returns> public static OracleDataReader RunProcedure(string storedProcName, IDataParameter[] parameters ) { OracleConnection connection = new OracleConnection(connectionString); OracleDataReader returnReader; connection.Open(); OracleCommand command = BuildQueryCommand( connection,storedProcName, parameters ); command.CommandType = CommandType.StoredProcedure; returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); return returnReader; } /// <summary> /// 执行存储过程 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="tableName">DataSet结果中的表名</param> /// <returns>DataSet</returns> public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName ) { using (OracleConnection connection = new OracleConnection(connectionString)) { DataSet dataSet = new DataSet(); connection.Open(); OracleDataAdapter sqlDA = new OracleDataAdapter(); sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters ); sqlDA.Fill( dataSet, tableName ); connection.Close(); return dataSet; } } /// <summary> /// 构建 OracleCommand 对象(用来返回一个结果集,而不是一个整数值) /// </summary> /// <param name="connection">数据库连接</param> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand</returns> private static OracleCommand BuildQueryCommand(OracleConnection connection,string storedProcName, IDataParameter[] parameters) { OracleCommand command = new OracleCommand( storedProcName, connection ); command.CommandType = CommandType.StoredProcedure; foreach (OracleParameter parameter in parameters) { command.Parameters.Add( parameter ); } return command; } /// <summary> /// 执行存储过程,返回影响的行数 /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <param name="rowsAffected">影响的行数</param> /// <returns></returns> public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected ) { using (OracleConnection connection = new OracleConnection(connectionString)) { int result; connection.Open(); OracleCommand command = BuildIntCommand(connection,storedProcName, parameters ); rowsAffected = command.ExecuteNonQuery(); result = (int)command.Parameters["ReturnValue"].Value; //Connection.Close(); return result; } } /// <summary> /// 创建 OracleCommand 对象实例(用来返回一个整数值) /// </summary> /// <param name="storedProcName">存储过程名</param> /// <param name="parameters">存储过程参数</param> /// <returns>OracleCommand 对象实例</returns> private static OracleCommand BuildIntCommand(OracleConnection connection,string storedProcName, IDataParameter[] parameters) { OracleCommand command = BuildQueryCommand(connection,storedProcName, parameters ); command.Parameters.Add( new OracleParameter ( "ReturnValue", OracleDbType.Int32, 4, ParameterDirection.ReturnValue, false,0,0,string.Empty,DataRowVersion.Default,null )); return command; } #endregion } }
出处:https://blog.csdn.net/u012949335/article/details/82378210
===========================================================
今天调用webservice的时候,运行程序后开始报错以下的错误信息
“/”应用程序中的服务器错误。 未能加载文件或程序集“Oracle.DataAccess”或它的某一个依赖项。试图加载格式不正确的程序。 说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息: System.BadImageFormatException: 未能加载文件或程序集“Oracle.DataAccess”或它的某一个依赖项。试图加载格式不正确的程序。 源错误: 执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。 程序集加载跟踪: 下列信息有助于确定程序集“Oracle.DataAccess”无法加载的原因......。
然后百度上搞了很久,各种方法试遍了,最后尝试用了Oracle.ManagedDataAccess Oracle全托管驱动,添加到项目的引用中,再配置一下Web.config,大功告成了。
下面贴上代码,以备以后需要。
<configSections> <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/> </configSections> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.data> <DbProviderFactories> <remove invariant="Oracle.ManagedDataAccess.Client"/> <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/> </DbProviderFactories> </system.data> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <publisherPolicy apply="no"/> <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/> <bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0"/> </dependentAssembly> </assemblyBinding> </runtime> <oracle.manageddataaccess.client> <version number="*"> <dataSources> <dataSource alias="SampleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) "/> </dataSources> </version> </oracle.manageddataaccess.client>
ORACLE全托管驱动Oracle.ManagedDataAccess.dll ,支持EF 支持分布式事务,连接数据库再也不需要安装oracle 客户端了,也不用区分32位,64位了。
Oracle.ManagedDataAccess.dll下载地址:http://download.csdn.net/detail/w3800/7360331
出处:https://www.cnblogs.com/handsomeso/p/5623146.html
===========================================================
ODP.NET Managed web.config 配置
<connectionStrings>
<add name="OracleConnectionString" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=scott;Password=tiger;Data Source=MyDataSource;PERSIST SECURITY INFO=True" />
</connectionStrings>
<oracle.manageddataaccess.client>
<version number="*"><dataSources>
<dataSource alias="SampleDataSource"
descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) "/>
<dataSource alias="MyDataSource"
descriptor="(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = tcp)(HOST = 192.168.0.1)(PORT = 1521)) (ADDRESS = (PROTOCOL = tcp)(HOST = 192.168.0.2)(PORT = 1521)) (LOAD_BALANCE = ON) (FAILOVER = ON) ) (CONNECT_DATA =(SERVICE_NAME = oradb)(GLOBAL_NAME = oradb)(FAILOVER_MODE = (TYPE = SELECT) (METHOD = BASIC)))) " />
</dataSources>
<settings>
<setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\"/>
</settings>
</version>
</oracle.manageddataaccess.client>
c#
public static string connectionString = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;// "连接字符串";
出处:https://blog.csdn.net/deepblue1974/article/details/52639396