asp.net Oracle数据库访问操作类

代码如下:

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OracleClient;
using System.Configuration;
using System.Data.Common;
using System.Collections.Generic;

/// <summary>
    /// 数据访问抽象基础类
    ///
    /// </summary>
public class DBBase
{

//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.       
    public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString();
    public DBBase()
    {
    }

#region 检查用户名是否存在
    /// <summary>
    /// 检查用户名是否存在,存在返回true,不存在返回false
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public static bool Exists(string strSql)
    {

using (OracleConnection connection = new OracleConnection(connectionString))
        {
            connection.Open();
            OracleCommand myCmd = new OracleCommand(strSql, connection);
            try
            { 
                object obj = myCmd.ExecuteScalar(); //返回结果的第一行一列
                myCmd.Parameters.Clear();
                if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                {
                    return false;
                }
                else
                {
                    return true;
                }          
            }
            catch (Exception ex)
             {
                 throw ex;
             }
       }
    }

#endregion

#region  执行简单SQL语句 返回影响的记录数

/// <summary>
    /// 执行SQL语句,返回影响的记录数
    /// </summary>
    /// <param name="SQLString">SQL语句</param>
    /// <returns>影响的记录数</returns>
    public static int ExecuteSql(string SQLString)
    {

OracleConnection connection = null;
        OracleCommand cmd = null;
        try
        {
            connection = new OracleConnection(connectionString);
            cmd = new OracleCommand(SQLString, connection);
            connection.Open();
            int rows = cmd.ExecuteNonQuery();
            return rows;
        }
        finally
        {
            if (cmd != null)
            {
                cmd.Dispose();
            }
            if (connection != null)
            {
                connection.Close();
                connection.Dispose();
            }
        }
    }
       #endregion

#region   执行查询语句,返回SqlDataReader
    /// <summary>
    /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close )
    /// </summary>
    /// <param name="strSQL">查询语句</param>
    /// <returns>SqlDataReader</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 (System.Data.OracleClient.OracleException e)
        {
            throw e;
        }
        finally
        {
            connection.Close();

}
    }
    #endregion

#region  执行SQL查询语句,返回DataTable数据表
    /// <summary>
    /// 执行SQL查询语句
    /// </summary>
    /// <param name="sqlStr"></param>
    /// <returns>返回DataTable数据表</returns>
    public static DataTable GetDataTable(string sqlStr)
    {
        OracleConnection mycon = new OracleConnection(connectionString);
        OracleCommand mycmd = new OracleCommand(sqlStr, mycon);
        DataTable dt = new DataTable();
        OracleDataAdapter da = null;
        try
        {
            mycon.Open();
            da = new OracleDataAdapter(sqlStr, mycon);
            da.Fill(dt);

}
        catch (Exception ex)
        {

throw new Exception(ex.ToString());
        }
        finally
        {
            mycon.Close();
        }
        return dt;
    }
    #endregion

#region 存储过程操作
    /// <summary>
    ///  运行存储过程,返回datatable;
    /// </summary>
    /// <param name="storedProcName">存储过程名称</param>
    /// <param name="parameters">参数</param>
    /// <returns></returns>
    public static DataTable RunProcedureDatatable(string storedProcName, IDataParameter[] parameters)
    {
        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            DataSet ds = new DataSet();
            connection.Open();
            OracleDataAdapter sqlDA = new OracleDataAdapter();
            sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
            sqlDA.Fill(ds);
            connection.Close();
            return ds.Tables[0];
        }
    }
    /// <summary>
    /// 执行存储过程
    /// </summary>
    /// <param name="storedProcName">存储过程名称</param>
    /// <param name="parameters">参数</param>
    /// <returns></returns>
    public static int RunProcedure(string storedProcName, IDataParameter[] parameters)
    {
        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            try
            {
                connection.Open();
                OracleCommand command = new OracleCommand(storedProcName, connection);
                command.CommandType = CommandType.StoredProcedure;
                foreach (OracleParameter parameter in parameters)
                {
                    if (parameter != null)
                    {
                        // 检查未分配值的输出参数,将其分配以DBNull.Value.
                        if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                            (parameter.Value == null))
                        {
                            parameter.Value = DBNull.Value;
                        }
                        command.Parameters.Add(parameter);
                    }
                }
               int rows = command.ExecuteNonQuery();
               return rows;
            }

finally
            {
                connection.Close();
            }
        }
    }

/// <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)
        {
            if (parameter != null)
            {
                // 检查未分配值的输出参数,将其分配以DBNull.Value.
                if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                    (parameter.Value == null))
                {
                    parameter.Value = DBNull.Value;
                }
                command.Parameters.Add(parameter);
            }
        }
        return command;
    }

#endregion

#region 事务处理

/// <summary>
    /// 执行多条SQL语句(list的形式),实现数据库事务。
    /// </summary>
    /// <param name="SQLStringList">多条SQL语句</param>   
    /// 调用 Transaction 对象的 Commit 方法来完成事务,或调用 Rollback 方法来取消事务。
    public static int ExecuteSqlTran(List<String> SQLStringList)
    {
        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            connection.Open();
            // 为事务创建一个命令
            OracleCommand cmd = new OracleCommand();
            cmd.Connection = connection;
            OracleTransaction tx = connection.BeginTransaction();// 启动一个事务
            cmd.Transaction = tx;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();//用Commit方法来完成事务
                return count;//
            }
            catch
            {
                tx.Rollback();//出现错误,事务回滚!
                return 0;
            }
            finally
            {
                cmd.Dispose();
                connection.Close();//关闭连接
            }
        }
    }
    #endregion
    #region 事务处理

/// <summary>
    /// 执行多条SQL语句(字符串数组形式),实现数据库事务。
    /// </summary>
    /// <param name="SQLStringList">多条SQL语句</param>   
    /// 调用 Transaction 对象的 Commit 方法来完成事务,或调用 Rollback 方法来取消事务。
    public static int ExecuteTransaction(string[] SQLStringList,int p)
    {
        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            connection.Open();
            // 为事务创建一个命令
            OracleCommand cmd = new OracleCommand();
            cmd.Connection = connection;
            OracleTransaction tx = connection.BeginTransaction();// 启动一个事务
            cmd.Transaction = tx;
            try
            {
                int count = 0;
                for (int n = 0; n < p; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Trim().Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                tx.Commit();//用Commit方法来完成事务
                return count;//
            }
            catch
            {
                tx.Rollback();//出现错误,事务回滚!
                return 0;
            }
            finally
            {
                cmd.Dispose();
                connection.Close();//关闭连接
            }
        }
    }

#endregion
    /// <summary>
    /// 执行存储过程获取所需编号(各表主键)
    /// </summary>
    /// <param name="FlowName">存储过程参数</param>
    /// <param name="StepLen">存储过程参数(默认为1)</param>
    /// <returns>编号(各表主键)</returns>
    public static string Get_FlowNum(string FlowName, int StepLen = 1)
    {
        OracleConnection mycon = new OracleConnection(connectionString);
        try
        {
            mycon.Open();
            OracleCommand MyCommand = new OracleCommand("ALARM_GET_FLOWNUMBER", mycon);
            MyCommand.CommandType = CommandType.StoredProcedure;
            MyCommand.Parameters.Add(new OracleParameter("I_FlowName", OracleType.VarChar, 50));
            MyCommand.Parameters["I_FlowName"].Value = FlowName;
            MyCommand.Parameters.Add(new OracleParameter("I_SeriesNum", OracleType.Number));
            MyCommand.Parameters["I_SeriesNum"].Value = StepLen;
            MyCommand.Parameters.Add(new OracleParameter("O_FlowValue", OracleType.Number));
            MyCommand.Parameters["O_FlowValue"].Direction = ParameterDirection.Output;
            MyCommand.ExecuteNonQuery();
            return MyCommand.Parameters["O_FlowValue"].Value.ToString();
        }
        catch
        {
            return "";
        }
        finally
        {
            mycon.Close();
        }
    }

}

(0)

相关推荐

  • 一个ASP.NET的MYSQL的数据库操作类自己封装的

    /** * 类说明:对MYSQL数据库的操作类 */ using System; using System.Data; using MySql.Data.MySqlClient; namespace Niunan.BYLW.Utility { /// <summary>对MYSQL数据库的操作类 /// /// </summary> public class MYSQLHelper { private MySqlConnection conn = null; private MyS

  • asp.net下使用DbProviderFactories的数据库操作类

    封装数据库操作,并且提供事务处理. 复制代码 代码如下: 使用DbProviderFactories的数据库操作类 Imports System.Data Imports System.Configuration Imports System.Data.Common '******************************************************************* '* Page/Class Name:XPDBHelper.vb '* Title:使用DbP

  • ASP.NET对SQLServer的通用数据库访问类

    本文模仿实现数据库访问的通用类,代码清晰,而且很实用,包括了对数据库的所有的常用的操作. /// <summary> /// 数据库访问通用类 /// </summary> public class SqlHelper { private string connectionString; /// <summary> /// 设定数据库访问字符串 /// </summary> public string ConnectionString { set { con

  • asp.net 数据库连接类代码(SQL)

    复制代码 代码如下: public class SqlOperation { #region 属性 /// <summary> /// 保存在Web.config中的连接字符串 /// </summary> protected static string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["hao"].ConnectionString; /

  • ASP.NET web.config中数据库连接字符串connectionStrings节的配置方法

    在ASP.NET开发的网站根目录,有一个名为web.config的文件,顾名思义,这是为整个网站进行配置的文件,其格式为XML格式.这里主要谈谈文件中的<connectionStrings>节. <connectionStrings>节是对连接到数据库的字符串进行配置,由于MS SQL Server与ASP.NET同属于微软的产品,因此是使用ASP.NET开发时首选的数据库是MS SQL Server,本文只讨论对MS SQL Server的连接字符串情况.第一种情况,本地开发时,

  • ASP.NET 6种常用数据库的连接方法

    1.C#连接连接Access 程序代码:     复制代码 代码如下: using   System.Data; using   System.Data.OleDb;    .. string   strConnection="Provider=Microsoft.Jet.OleDb.4.0;";     strConnection+=@"Data   Source=C:BegASPNETNorthwind.mdb"; OleDbConnection   objCo

  • ASP.NET2.0 SQL Server数据库连接详解

    Connection类有四种:SqlConnection,OleDbConnection,OdbcConnection和OracleConnection. SqlConnection类的对象连接SQL Server数据库:OracleConnection 类的对象连接Oracle数据库: OleDbConnection类的对象连接支持OLE DB的数据库,如Access:而OdbcConnection类的对象连接任何支持ODBC的数据库.与数据库的所有通讯最终都是通过Connection对象来完

  • ASP.NET数据库操作类实例

    本文实例讲述了ASP.NET数据库操作类.分享给大家供大家参考,具体如下: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Syst

  • asp.net连接查询SQL数据库并把结果显示在网页上(2种方法)

    在ASP.NET中,使用C#连接SQL数据库,并使用SQL语句查询,以前从来没有接触过C#,最近用到了,摸索了两天终于运行起来了,Mark一下,不喜勿喷 有两种方法:(说的是第一种方法不安全,我也不清楚^_^) 第一种方法: 复制代码 代码如下: //建立ASP.NET Web 应用程序,直接在Page_load函数中加入一下代码,貌似就可以用了 public void Page_Load(object sender, EventArgs e) { using (SqlConnection co

  • ASP.NET封装的SQL数据库访问类

    using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Collections; namespace MyCorporation.DepartMent.DataBase { /// <summary> /// 通用数据库类 /// </summary> public class DataBase { private string Co

  • asp.net 数据库的连接和datatable类

    using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.D

  • asp.net下Oracle,SQL Server,Access万能数据库通用类

    复制代码 代码如下: using System; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Data.OleDb; using System.Data.OracleClient; using System.Configuration; using System.Reflection; nam

  • Asp.net把图片存入数据库和读取图片的方法

    网上关于ASP.NET上传图片到数据库的资料非常多,常用的如下:存储图片类型数据有以下几种方式:1.将图片转换为二进制数组(byte[]) 复制代码 代码如下: byte[] fileData = this.FileUpload1.FileBytes; 2. 根据路径将文件转换为2进制数组 复制代码 代码如下: 代码 public byte[] returnbyte(string strpath){ // 以二进制方式读文件    FileStream fsMyfile = new FileSt

随机推荐