Self-use sqlhelper

I occasionally use ado.net at work, but I have never had my own sqlhelper, so I feel a little chaotic online. I took the time to organize one myself today. The function is simple, but it can be used in most cases. It supports sql, stored procedures, and transactions.

public static class SqlHelper
    {
        private static readonly string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["mssqlserver"].ConnectionString;

        #region usage example
        //string sql = "update [User] set Name=@name where Id=@id";
        //SqlParameter[] pms = new SqlParameter[]{
        //        new SqlParameter("name",SqlDbType.NVarChar,20){Value="xc"},
        //        new SqlParameter("id",SqlDbType.Int){Value=1}
        //    };
        //int n = SqlHelper.ExecuteNonQuery(sql, CommandType.Text, pms);
        #endregion

        /// <summary>
        /// Execute a sql or stored procedure that returns the number of rows affected
        /// </summary>
        /// <param name="cmdText">sql, stored procedure name</param>
        /// <param name="cmdType">CommandType.Text,CommandType.StoredProcedure</param>
        /// <param name="pms">sql or procedure parameters, if there is no such parameter, pass null</param>
        /// <returns>Returns the number of affected rows</returns>
        public static int ExecuteNonQuery(string cmdText, CommandType cmdType, params SqlParameter[] pms)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdText, con))
                {
                    cmd.CommandType = cmdType;
                    if (pms != null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// Execute a sql or stored procedure that returns a single value
        /// </summary>
        /// <param name="cmdText">sql或procedure</param>
        /// <param name="cmdType">CommandType.Text,CommandType.StoredProcedure</param>
        /// <param name="pms">sql or procedure parameters, if there is no such parameter, pass null</param>
        /// <returns>Returns a single value</returns>
        public static object ExecuteScalar(string cmdText, CommandType cmdType, params SqlParameter[] pms)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(cmdText, con))
                {
                    cmd.CommandType = cmdType;
                    if (pms != null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }

        /// <summary>
        /// Execute the sql or stored procedure that returns the DataReader
        /// After reading, you need to manually close the SqlDataReader
        /// </summary>
        /// <param name="cmdText">sql或procedure</param>
        /// <param name="cmdType">CommandType.Text,CommandType.StoredProcedure</param>
        /// <param name="pms">sql or procedure parameters, if there is no such parameter, pass null</param>
        /// <returns>返回DataReader</returns>
        public static SqlDataReader ExecuteReader(string cmdText, CommandType cmdType, params SqlParameter[] pms)
        {
            SqlConnection con = new SqlConnection(conStr);
            using (SqlCommand cmd = new SqlCommand(cmdText, con))
            {
                cmd.CommandType = cmdType;
                if (pms != null) cmd.Parameters.AddRange(pms);
                try
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch (SqlException ex)
                {
                    con.Close();
                    with.Dispose ();
                    throw ex;
                }
            }
        }

        /// <summary>
        /// Execute the sql or stored procedure that returns the DataTable
        /// </summary>
        /// <param name="cmdText">sql或procedure</param>
        /// <param name="cmdType">CommandType.Text,CommandType.StoredProcedure</param>
        /// <param name="pms">sql or procedure parameters, if there is no such parameter, pass null</param>
        /// <returns>返回DataTable</returns>
        public static DataTable ExecuteDataTable(string cmdText, CommandType cmdType, params SqlParameter[] pms)
        {
            DataTable dt = new DataTable();
            using (SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conStr))
            {
                adapter.SelectCommand.CommandType = cmdType;
                if (pms != null)
                {
                    adapter.SelectCommand.Parameters.AddRange(pms);
                }
                adapter.Fill(dt);
            }
            return dt;
        }

        /// <summary>
        /// Execute multiple sql statements within a transaction that return the number of rows affected
        /// </summary>
        /// <param name="list">KeyValuePair<string, SqlParameter[]>集合,Key=sql,Value=params</param>
        /// <param name="cmdType">CommandType.Text,CommandType.StoredProcedure</param>
        /// <returns>Returns the number of affected rows</returns>
        public static int ExecuteNonQueryTransaction(List<KeyValuePair<string, SqlParameter[]>> list, CommandType cmdType)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                con.Open();
                SqlTransaction tx = con.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
                try
                {
                    int count = 0;
                    cmd.Connection = con;
                    cmd.Transaction = tx;
                    cmd.CommandType = cmdType;
                    foreach (var item in list)
                    {
                        string sql = item.Key;
                        if (!string.IsNullOrEmpty(sql)) cmd.CommandText = sql;
                        SqlParameter[] pms = item.Value;
                        if (pms != null) cmd.Parameters.AddRange(pms);
                        count += cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    tx.Commit();
                    return count;
                }
                catch (SqlException ex)
                {
                    tx.Rollback();
                    throw ex;
                }
                finally
                {
                    tx.Dispose();
                    cmd.Dispose();
                }
            }
        }
    }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764076&siteId=291194637