oracleHelper 操作帮助类

时间:2022-05-04 09:09:28
 using System;
using System.Configuration;
using System.Data;
using System.Collections;
using Oracle.DataAccess.Client; namespace Cont.DAL.Leave
{
/// <summary>
///Oracle数据库操作帮助类
/// </summary>
public class OracleHelper
{
//从配置文件中读取配置好的连接字符串
private static OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
private static OracleTransaction tran = null; /// <summary>
/// 返回受影响的行数
/// </summary>
/// <param name="sql">sql语句</param>
/// <returns></returns>
public static int NonQuery(string sql)
{
try
{
OracleCommand cmd = new OracleCommand(sql, conn);
int i = cmd.ExecuteNonQuery();
return i;//将受影响的行数返回
}
catch (Exception se)
{
throw se;
} }
/// <summary>
/// 返回一个临时表数据,一般执行显示表中多条数据操作 select
/// </summary>
/// <param name="sql">要执行的查询sql语句</param>
/// <returns>返回一个DataTable</returns>
public static DataTable GetTable(string sql)
{
try
{
conn.Open();
OracleDataAdapter sda = new OracleDataAdapter(sql, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
catch (Exception se)
{
throw se;
}
finally
{
conn.Close();
} }
/// <summary>
/// 执行查询操作,返回一个结果集
/// </summary>
/// <param name="sql">要执行的sql语句</param>
/// <returns>返回一个读取器</returns>
public static OracleDataReader Reader(string sql)
{
try
{
conn.Open();
OracleCommand cmd = new OracleCommand(sql, conn);
OracleDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);//读取器和数据源此处不能被关闭
return sdr;
}
catch (Exception se)
{
throw se;
}
}
/// <summary>
/// 执行查询操作,返回一个单值,一般执行根据名称找编号或执行聚合函数
/// </summary>
/// <param name="sql">要执行的sql查询语句</param>
/// <returns>返回一个object类型</returns>
public static object Scalar(string sql)
{
try
{
conn.Open();
OracleCommand cmd = new OracleCommand(sql, conn);
object obj = cmd.ExecuteScalar();
return obj;
}
catch (Exception se)
{
throw se;
}
finally
{
conn.Close();
}
} /// <summary>
///开始事务
/// </summary>
public static void BeginTran()
{
conn.Open();
tran = conn.BeginTransaction();
} /// <summary>
/// 提交事务
/// </summary>
public static void CommitTran()
{
tran.Commit();
tran.Dispose();
conn.Close();
tran = null;
} /// <summary>
/// 回滚
/// </summary>
public static void RollbackTran()
{
tran.Rollback();
tran.Dispose();
conn.Close();
tran = null;
}
}
}