Let's go

C# 通用数据访问类

一、原始方法

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace SaiAo.UI.Helper
{
    public class SqlHelper
    {
        private static readonly string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
        /// <summary>
        /// 执行增删改的方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int Update(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        /// <summary>
        /// 结果集中的第一行的第一列
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static object Update1(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        /// <summary>
        /// 执行一个结果集的查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static SqlDataReader GetReader(string sql)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                conn.Close();
                throw ex;
            }
        }
    }
}

调用:

public void Test()
        {
            string sql = "select AdminName,* from user where usercode={0}";
            sql = string.Format(sql,"admin");
            try
            {
                SqlDataReader objReader = SqlHelper.GetReader(sql);
                if (objReader.Read())
                {
                    //取值
                    objReader["AdminName"].ToString();
                    objReader.Close();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("应用程序或数据库出现错误"+ex.Message);
            }
        }
View Code

 

二、

 

posted @ 2020-11-26 22:48  chenze  阅读(274)  评论(0编辑  收藏  举报
有事您Q我