当前位置:数据库 > SQLServer >>

步步为营 .NET三层架构解析 三、SQLHelper设计

数据库设计好了,我们开始设计SQLHelper了,是一个SQL基类.

 连接数据源:

    private SqlConnection myConnection = null;
    private readonly string RETURNVALUE = "RETURNVALUE";

打开数据库连接.

 private void Open()
        {
            // 打开数据库连接
            if (myConnection == null)
            {
               //    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
               myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
           
            }
            if (myConnection.State == ConnectionState.Closed)
            {
                try
                {
                    ///打开数据库连接
                    myConnection.Open();
                }
                catch (Exception ex)
                {
                   
                    SystemError.CreateErrorLog(ex.Message);
                }
                finally
                {
                    ///关闭已经打开的数据库连接    
                }
            }
        }

关闭数据库连接

 public void Close()
        {
            ///判断连接是否已经创建
            if (myConnection != null)
            {
                ///判断连接的状态是否打开
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
            }
        }

释放资源

        public void Dispose()
        {
            // 确认连接是否已经关闭
            if (myConnection != null)
            {
                myConnection.Dispose();
                myConnection = null;
            }
        }

执行无参数和返回int型的存储过程

public int RunProc(string procName)
        {
            SqlCommand cmd = CreateProcCommand(procName, null);
            try
            {
                ///执行存储过程
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                ///记录错误日志
                SystemError.CreateErrorLog(ex.Message);
            }
            finally
            {
                ///关闭数据库的连接
                Close();
            }

            ///返回存储过程的参数值
            return (int)cmd.Parameters[RETURNVALUE].Value;
        }

执行传入参数和返回int型的存储过程

public int RunProc(string procName, SqlParameter[] prams)
        {
            SqlCommand cmd = CreateProcCommand(procName, prams);
            try
            {
                ///执行存储过程
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                ///记录错误日志
                SystemError.CreateErrorLog(ex.Message);
            }
  &n

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,