抽象工厂设计模式(3)--SqlHelper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SQLServerService
{
    class SqlHelper
    {

        #region 连接

        /// <summary>
        /// 连接字符串名,配置文件中的连接字符串名称
        /// </summary>
        private const String ConnectionStringName = "SQLCon";
        /// <summary>
        /// 连接字符串,其中包含源数据库名称和建立初始连接所需的其他参数。
        /// </summary>
        private static String _ConnectionString;
        /// <summary>
        /// 连接字符串,其中包含源数据库名称和建立初始连接所需的其他参数。
        /// </summary>
        private static String ConnectionString
        {
            get
            {
                if (String.IsNullOrEmpty(_ConnectionString))
                {
                    _ConnectionString = GetConnectionStringFromEnvironmentVariable();
                    if (String.IsNullOrEmpty(_ConnectionString))
                    {
                        ConnectionStringSettings connSettings = ConfigurationManager.ConnectionStrings[ConnectionStringName];
                        if (connSettings == null || String.IsNullOrEmpty(connSettings.ConnectionString))
                            throw new Exception("请确认连接字符串" + ConnectionStringName + "配置是否正确");
                        _ConnectionString = connSettings.ConnectionString;
                    }
                }
                return _ConnectionString;
            }
        }
        /// <summary>
        /// 从环境变更配置的配置文件中获取连接字符串
        /// </summary>
        /// <returns>连接字符串,查询失败时返回null</returns>
        private static String GetConnectionStringFromEnvironmentVariable()
        {
            String environmentVariableName = ConfigurationManager.AppSettings["连接字符串配置文件环境变量名"];
            if (String.IsNullOrEmpty(environmentVariableName))
                return null;
            String configPath = System.Environment.GetEnvironmentVariable(environmentVariableName, EnvironmentVariableTarget.Machine);
            if (String.IsNullOrEmpty(configPath))
                return null;

            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = configPath;

            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            if (config.ConnectionStrings == null || !config.HasFile)
                return null;
            ConnectionStringSettings connSettings = config.ConnectionStrings.ConnectionStrings[ConnectionStringName];
            if (connSettings == null)
                return null;
            if (String.IsNullOrEmpty(connSettings.ConnectionString))
                return null;

            return connSettings.ConnectionString;
        }

        #endregion



        #region 获得参数对象
        /// <summary>
        ///  获得参数对象 
        /// </summary>
        /// <param name="paramName">参数名称</param>
        /// <param name="paramType">数据类型</param>
        /// <param name="paramValue">参数实值</param>
        /// <returns></returns>
        public static SqlParameter GetParameter(String paramName, DbType paramType, Object paramValue)
        {
            SqlParameter param = new SqlParameter(paramName, paramValue);
            param.DbType = paramType;
            return param;
        }

        /// <summary>
        /// 获得参数对象 
        /// </summary>
        /// <param name="paramName">参数名称</param>
        /// <param name="paramValue">参数实值</param>
        /// <returns></returns>
        public static SqlParameter GetParameter(string paramName, string paramValue)
        {
            SqlParameter param = new SqlParameter(paramName, paramValue);
            return param;
        }
        #endregion

        #region 执行SQL语句,返回执行行数
        /// <summary>
        /// 执行SQL语句,返回执行行数
        /// </summary>
        /// <param name="Sqlstr">SQL语句</param>
        /// <param name="param">参数对象数组</param>
        /// <returns></returns>
        public static int ExecuteSql(String Sqlstr, SqlParameter[] param)
        {

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandText = Sqlstr;
                    cmd.Parameters.AddRange(param);
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                    conn.Close();
                    return i;
                }
                catch (Exception ex)
                {
                    WriteLog.Write("ExecuteSql修改数据库出错:" + ex.ToString());
                    return 0;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
        /// <summary>
        /// 执行SQL语句,返回执行行数
        /// </summary>
        /// <param name="Sqlstr">SQL语句</param>
        /// <param name="param">参数对象数组</param>
        /// <returns></returns>
        public static int ExecuteSql(String Sqlstr)
        {

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = conn;
                    cmd.CommandText = Sqlstr;
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                    conn.Close();
                    return i;
                }
                catch (Exception ex)
                {
                    WriteLog.Write("ExecuteSql修改数据库出错:" + ex.ToString());
                    return 0;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
        #endregion

        #region 执行SQL语句返回数据表
        /// <summary>
        /// 执行SQL语句并返回数据表
        /// </summary>
        /// <param name="Sqlstr">SQL语句</param>
        /// <returns></returns>
        public static DataTable ExecuteDt(String Sqlstr)
        {

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                try
                {
                    SqlDataAdapter da = new SqlDataAdapter(Sqlstr, conn);
                    DataTable dt = new DataTable();
                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    return dt;
                }
                catch (Exception ex)
                {
                    WriteLog.Write("ExecuteDt查询数据库出错:" + ex.ToString());
                    return null;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }

        }
        /// <summary>
        /// 执行SQL语句并返回数据表
        /// </summary>
        /// <param name="Sqlstr">SQL语句</param>
        /// <param name="param">参数对象列表</param>
        /// <returns></returns>
        public static DataTable ExecuteDt(String Sqlstr, SqlParameter[] param)
        {

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                try
                {
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter();
                    SqlCommand cmd = new SqlCommand(Sqlstr, conn);
                    cmd.Connection = conn;
                    cmd.Parameters.AddRange(param);
                    da.SelectCommand = cmd;
                    conn.Open();
                    da.Fill(dt);
                    conn.Close();
                    return dt;
                }
                catch (Exception ex)
                {
                    WriteLog.Write("ExecuteDt查询数据库出错:" + ex.ToString());
                    return null;
                }
                finally
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
        #endregion

        /// <summary>
        /// 批量执行SQL语句
        /// </summary>
        /// <param name="Sqlstr">SQL语句数组</param>
        /// <param name="param">SQL参数对象数组</param>
        /// <returns></returns>
        public static Int32 ExecuteSqls(String[] Sqlstr, List<SqlParameter[]> param)
        {

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {

                SqlCommand cmd = new SqlCommand();
                SqlTransaction tran = null;
                cmd.Transaction = tran;
                try
                {
                    conn.Open();
                    tran = conn.BeginTransaction();
                    cmd.Connection = conn;
                    cmd.Transaction = tran;

                    Int32 count = Sqlstr.Length;
                    for (Int32 i = 0; i < count; i++)
                    {
                        cmd.CommandText = Sqlstr[i];
                        cmd.Parameters.AddRange(param[i]);
                        cmd.ExecuteNonQuery();
                    }
                    tran.Commit();
                    return 1;
                }
                catch
                {
                    tran.Rollback();
                    return 0;
                }
                finally
                {
                    cmd.Dispose();
                    conn.Close();
                }
            }
        }
    }
}

调用:

       /// <summary>
        /// 用户管理信息查询
        /// </summary>
        /// <returns></returns>
        public DataTable Userlist(string username)
        {
            StringBuilder sqlSB = new StringBuilder();
            sqlSB.Append("select a.ID,a.USERNAME,a.CJSJ,a.E_MAIL,a.PHONENUMBER,b.ROLE_NAME from OIL_USER a left join  OIL_ROLE b on  a.ROLE = b.id");
            sqlSB.Append(" Order by a.CJSJ desc");
            return SqlHelper.ExecuteDt(sqlSB.ToString());
        }

        /// <summary>
        /// 新建用户
        /// </summary>
        /// roless为角色ID
        /// <param name="user">用户对象</param>
        public int CreatAddUser(UserListVo userlist)
        {
            StringBuilder sqlSB = new StringBuilder();
            sqlSB.Append("insert into OIL_USER(id,USERNAME,\"PASSWORD\",CJSJ,\"ROLE\",E_MAIL,PHONENUMBER) values(@id,@username,@passwords,@usertime,@roless,@email,@PHONENUMBER)");
            SqlParameter[] pa ={
                        SqlHelper.GetParameter("@id", DbType.String,  Guid.NewGuid().ToString()),
                        SqlHelper.GetParameter("@username", DbType.String, userlist.UserName),
                        SqlHelper.GetParameter("@passwords", DbType.String, userlist.Password),
                        SqlHelper.GetParameter("@usertime", DbType.DateTime, userlist.CJSZ),
                        SqlHelper.GetParameter("@roless", DbType.String, userlist.ROLE),
                        SqlHelper.GetParameter("@email", DbType.String, userlist.E_MAIL),
                        SqlHelper.GetParameter("@PHONENUMBER", DbType.String, userlist.PHONENUMBER),
                                  };
            return SqlHelper.ExecuteSql(sqlSB.ToString(), pa);
        }

 

猜你喜欢

转载自blog.csdn.net/wanglijia26/article/details/89314766
0条评论
添加一条新回复