asp.net Oracle database access operation class

  • 2020-05-30 19:50:16
  • OfStack


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>
    ///  Data access abstract base class 
    /// 
    /// </summary>
public class DBBase
{
 
    // Database connection string (web.config To configure the ) , which can be changed dynamically connectionString Support for multiple databases .        
    public static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString();
    public DBBase()
    {
    }
    #region  Check to see if the username exists 
    /// <summary>
    ///  Check to see if the username exists and return it true , there is no return 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(); // Returns the first of the results 1 line 1 column 
                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   Perform simple SQL statements   Returns the number of records affected 
    /// <summary>
    ///  perform SQL Statement that returns the number of records affected 
    /// </summary>
    /// <param name="SQLString">SQL statements </param>
    /// <returns> Number of records affected </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    Execute the query and return SqlDataReader
    /// <summary>
    ///  Execute the query and return SqlDataReader (  Note: after calling this method, 1 Set to SqlDataReader for Close )
    /// </summary>
    /// <param name="strSQL"> The query </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   perform SQL Query statement, return DataTable The data table 
    /// <summary>
    ///  perform SQL The query 
    /// </summary>
    /// <param name="sqlStr"></param>
    /// <returns> return DataTable The data table </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  Stored procedure operation 
    /// <summary>
    ///   Running stored procedures , return datatable;
    /// </summary>
    /// <param name="storedProcName"> Stored procedure name </param>
    /// <param name="parameters"> parameter </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>
    ///  Executing stored procedures 
    /// </summary>
    /// <param name="storedProcName"> Stored procedure name </param>
    /// <param name="parameters"> parameter </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)
                    {
                        //  Check output parameters for unassigned values , Distribute it to 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>
    ///  build  OracleCommand  object ( Used to return 1 It's a result set, not a result set 1 An integer value )
    /// </summary>
    /// <param name="connection"> Database connection </param>
    /// <param name="storedProcName"> Stored procedure name </param>
    /// <param name="parameters"> Stored procedure parameter </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)
            {
                //  Check output parameters for unassigned values , Distribute it to 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  Transaction processing 
    /// <summary>
    ///  To perform multiple SQL statements (list In the form of ) , to implement database transactions. 
    /// </summary>
    /// <param name="SQLStringList"> multiple SQL statements </param>    
    ///  call  Transaction  The object's  Commit  Method to complete the transaction, or call  Rollback  Method to cancel the transaction. 
    public static int ExecuteSqlTran(List<String> SQLStringList)
    {
        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            connection.Open();
            //  Create for the transaction 1 A command 
            OracleCommand cmd = new OracleCommand();
            cmd.Connection = connection;
            OracleTransaction tx = connection.BeginTransaction();//  Start the 1 A transaction 
            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();// with Commit Method to complete the transaction 
                return count;//
            }
            catch
            {
                tx.Rollback();// Error, transaction rollback! 
                return 0;
            }
            finally
            {
                cmd.Dispose();
                connection.Close();// Close the connection 
            }
        }
    }
    #endregion
    #region  Transaction processing 
    /// <summary>
    ///  To perform multiple SQL statements ( String array form ) , to implement database transactions. 
    /// </summary>
    /// <param name="SQLStringList"> multiple SQL statements </param>    
    ///  call  Transaction  The object's  Commit  Method to complete the transaction, or call  Rollback  Method to cancel the transaction. 
    public static int ExecuteTransaction(string[] SQLStringList,int p)
    {
        using (OracleConnection connection = new OracleConnection(connectionString))
        {
            connection.Open();
            //  Create for the transaction 1 A command 
            OracleCommand cmd = new OracleCommand();
            cmd.Connection = connection;
            OracleTransaction tx = connection.BeginTransaction();//  Start the 1 A transaction 
            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();// with Commit Method to complete the transaction 
                return count;//
            }
            catch
            {
                tx.Rollback();// Error, transaction rollback! 
                return 0;
            }
            finally
            {
                cmd.Dispose();
                connection.Close();// Close the connection 
            }
        }
    }
    #endregion
    /// <summary>
    ///  Execute the stored procedure to get the required number (each table primary key) 
    /// </summary>
    /// <param name="FlowName"> Stored procedure parameter </param>
    /// <param name="StepLen"> Stored procedure parameter (default is 1 ) </param>
    /// <returns> Number (each table primary key) </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();
        }
    }
}


Related articles: