C#工具类 SqlHelper

    public class SqlHelper
    {
        private static readonly string SqlConnStr = AppConfig.SqlConnStr;
        
        //查询DT
        public static DataTable QueryDataTable(string sql, object param = null)
        {
            SqlConnection conn = null;
            SqlCommand sqlCommand = null;
            SqlDataReader sqlDataReader = null;
            try
            {
                conn = new SqlConnection(SqlConnStr);
                conn.Open();
                
                sqlCommand = new SqlCommand(sql, conn);
                if (param != null) AddParam(sqlCommand, param);
                sqlDataReader = sqlCommand.ExecuteReader();
                
                DataTable dt = new DataTable();
                dt.Load(sqlDataReader);
                return dt;
            }
            catch (Exception e)
            {
                LogHelper.AddLog($"Sql查询异常:{e.Message} [{sql}]");
                return null;
            }
            finally
            {
                sqlDataReader?.Dispose();
                sqlCommand?.Dispose();
                conn?.Close();
            }
        }
        
        public static int Excute(string sql, object param = null)
        {
            SqlConnection conn = null;
            SqlCommand sqlCommand = null;
            try
            {
                conn = new SqlConnection(SqlConnStr);
                sqlCommand = new SqlCommand(sql, conn);
                if (param != null) AddParam(sqlCommand, param);
                conn.Open();
                return sqlCommand.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                LogHelper.AddLog($"Sql操作异常:{e.Message} [{sql}]");
                return -1;
            }
            finally
            {
                sqlCommand?.Dispose();
                conn?.Close();
            }
        }

        //动态添加sql参数
        private static void AddParam(SqlCommand sqlCommand, object param)
        {
            PropertyInfo[] properties = param.GetType().GetProperties();
            int size = properties.Length;
            if (size == 0) return;

            for (int i = 0; i < size; i++)
            {
                PropertyInfo property = properties[i];
                object value = property.GetValue(param);
                string name = property.Name;
                if (value != null && !string.IsNullOrEmpty(value.ToString()))
                {
                    sqlCommand.Parameters.AddWithValue(name, value);
                }else
                {
                    sqlCommand.Parameters.AddWithValue(name, DBNull.Value);
                }
            }
        }
        

   
    }

**尝试过像Java一样转化为实体类,最后发现还是DataTable好用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值