简体   繁体   中英

How can this database connection class be improved? (ADO.NET)

I am attempting to create a database access layer. I am looking for some improvements to this class/recommendations on best practice. It would be helpful if someone could point me to documentation on how this could be potentially done/things to consider. I have looked at using entity framework but it does not seem applicable, however, should I really be looking to move to EF? Is ADO.NET an outdated way of doing this?

    public static IDbCommand GetCommandObject(string Connstring)
    {
        IDbConnection conn = new SqlConnection(Connstring);
        return new SqlCommand { Connection = (SqlConnection)conn };
    }

    public static void AddParameter(ref IDbCommand cmd, string Name, object value, DbType ParamType)
    {
        IDbDataParameter Param = cmd.CreateParameter();
        Param.DbType = ParamType;
        Param.ParameterName = (Name.StartsWith("@")) ? "" : "@"; //@ character for MS SQL database
        Param.Value = value;

        cmd.Parameters.Add(Param);
    }

    public static Int32 ExecuteNonQuery(string SQL, IDbCommand cmd = null)
    {
        Boolean CommitTrans = true;
        Boolean CloseConn = true;
        SqlTransaction Trans = null;

        try
        {
            //IF Required - create command object if required
            if (cmd == null) { cmd = DB.GetCommandObject(""); }

            //Add the commandtext
            cmd.CommandText = SQL;

            if (cmd.Connection == null) { throw new Exception("No connection set"); }

            //IF REQUIRED - open the connection
            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            else
            {
                CloseConn = false;
            }

            if (cmd.Transaction != null)
            {
                //We have already been passed a Transaction so dont close it
                CommitTrans = false;
            }
            else
            {
                //Create and open a new transaction
                Trans = (SqlTransaction)cmd.Connection.BeginTransaction();
                cmd.Transaction = Trans;
            }

            Int32 rtn = cmd.ExecuteNonQuery();

            if (CommitTrans == true) { Trans.Commit(); }

            return rtn;
        }
        catch (Exception e)
        {
            if (CommitTrans == true) { Trans.Rollback(); }

            throw new Exception();
        }
        finally
        {
            if (CloseConn == true)
            {
                cmd.Connection.Close();
                cmd = null;
            }

        }

    }

    public static object ExecuteScalar(string SQL, IDbCommand cmd, Boolean NeedsTransaction = true)
    {
        Boolean CommitTrans = true;
        Boolean CloseConn = true;
        SqlTransaction Trans = null;

        try
        {
            //IF Required - create command object if required
            if (cmd == null) { cmd = DB.GetCommandObject(""); }

            //Add the commandtext
            cmd.CommandText = SQL;

            //IF REQUIRED - create default Connection to CourseBuilder DB
            if (cmd.Connection == null) { throw new Exception("No Connection Object"); }

            //IF REQUIRED - open the connection
            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            else
            {
                CloseConn = false;
            }

            if (NeedsTransaction == true)
            {
                if (cmd.Transaction != null)
                {
                    //We have already been passed a Transaction so dont close it
                    CommitTrans = false;
                }
                else
                {
                    //Create and open a new transaction
                    Trans = (SqlTransaction)cmd.Connection.BeginTransaction();
                    cmd.Transaction = Trans;
                }
            }

            Object rtn = cmd.ExecuteScalar();

            if (NeedsTransaction == true && CommitTrans == true) { Trans.Commit(); }

            return rtn;
        }
        catch
        {
            if (NeedsTransaction == true && Trans != null) { Trans.Rollback(); }
            throw new Exception();
        }
        finally
        {
            if (CloseConn == true) { cmd.Connection.Close(); cmd = null; }
        }



    }

    public static DataRow GetDataRow(string SQL, IDbCommand cmd = null, Boolean ErrorOnEmpty = true)
    {
        var dt = FillDatatable(SQL, ref cmd);
        if (dt.Rows.Count > 0)
        {
            return dt.Rows[0];
        }
        else
        {
            if (ErrorOnEmpty == true) { throw new Exception(nameof(GetDataRow) + " returned no rows."); }
            return null;
        }
    }

    public static DataTable FillDatatable(string SQL, ref IDbCommand cmd)
    {

        string newline = System.Environment.NewLine;
        var DT = new DataTable();
        Boolean LeaveConOpen = false;

        try
        {
            //Add the commandtext
            cmd.CommandText = SQL;

            //IF REQUIRED - create default Connection to CourseBuilder DB
            if (cmd?.Connection == null) { throw new Exception("No Connection Object"); }

            if (cmd.Connection.State != ConnectionState.Open)
            {
                cmd.Connection.Open();
                LeaveConOpen = false;
            }
            else
            {
                LeaveConOpen = true;
            }

            var DA = new SqlDataAdapter((SqlCommand)cmd);
            DA.Fill(DT);
        }
        catch (Exception ex)
        {
            var sbErr = new StringBuilder();

            sbErr.AppendLine("Parameters (type defaults to varchar(max)):" + newline);
            foreach (SqlParameter p in cmd.Parameters)
            {
                string s = "";
                sbErr.AppendLine("declare " + p.ParameterName + " varchar(max) = '" + (p.Value == DBNull.Value ? "Null" : p.Value + "'; ") + newline);
            }

            sbErr.AppendLine(newline + SQL + newline);

            throw new Exception("Failed to FillDataTable:" + newline + newline + sbErr.ToString(), ex);

        }
        finally
        {
            if (LeaveConOpen == false) { cmd.Connection.Close(); }

        }

        return DT;

    }

    public static T CheckNull<T>(T value, T DefaultValue)
    {
        if (value == null || value is System.DBNull)
        {
            return DefaultValue;

        }
        else
        {
            return value;
        }
    }

Couple of things to keep in mind when you are creating a DAL

  • DAL should be able to cater to multiple Databases (oracle , sql , mysql etc..)
  • You should have minimum of DB , Connection , Command and Reader implementations of each.
  • Do not worry about the connection pool
  • Be aware of the transaction scope , Especially when you are trying to save nested objects. (For Eg: by saving company, you are saving Company and Company.Employees and Employee.Phones in a single transaction)

Alternative is to use something like Dapper.

enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM