首页 > 数据库 >续《基于C# 开发的SOL SERVER 操作数据库类(SQLHelp》 ——第二弹

续《基于C# 开发的SOL SERVER 操作数据库类(SQLHelp》 ——第二弹

时间:2022-10-06 19:45:33浏览次数:58  
标签:SQLHelp string C# List SOL dic int new tb

续上一节,本节给出SQLHelp的具体实现方法——《YSFSQLHelp》,个人根据自己需要新建适合的类,本节根据参考网上资料,根据自己的需要编写的SQL帮助类。下面直接给出具体实现:

        //Data Source=.;Initial Catalog=SEFEvaluation;Persist Security Info=True;User ID=sa;Password=***********
        public static string SqlHost = GetConfig.GetConfiguration("ConnectionStrings:SqlHost");
        public static string SqlAdminName = GetConfig.GetConfiguration("ConnectionStrings:SqlAdminName");
        public static string SqlAdminPswd = GetConfig.GetConfiguration("ConnectionStrings:SqlAdminPswd");
        public static string SqlCatalogProFix = GetConfig.GetConfiguration("ConnectionStrings:SqlCatalogProFix");
        public static string strcon = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=true", SqlHost, SqlAdminName, SqlAdminPswd, SqlCatalogProFix);

       // public static string strcon = "Server=8.135.110.228;Initial Catalog=TestDB;User ID=sa;Password=QVq4iu=yV$ge7*qQ.6e,yL|hg!8d-79.,@yv?P=hj/JB72sd567";
        //数据库连接字符串(web.config来配置)
        //<add key="ConnectionString" value="server=127.0.0.1;database=DATABASE;uid=sa;pwd=" />  
        #region 类中的全局变量-数据连接字符串  
        // public static string strcon = "Data Source=127.0.0.1;User ID=sa;Password=family962464QR;Initial Catalog=SEFEvaluation;Pooling=true";//连接字符串,使用Windows登录方式
        // public static string strcon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString();//连接字符串,使用Windows登录方式
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数,初始化时连接数据库
        /// </summary>
        public YSFSQLHelp()
            {
                strcon = strcon;// ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString();
            }
            #endregion
            #region 其他转化与编码
            /// <summary>
            /// MD5加密
            /// </summary>
            /// <param name="strPwd">被加密的字符串</param>
            /// <returns>返回加密后的字符串</returns>
            public string GetMD5(string strPwd)
            {
                string pwd = "";
                //实例化一个md5对象
                MD5 md5 = MD5.Create();
                // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择
                byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(strPwd));
                //翻转生成的MD5码        
                s.Reverse();
                //通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
                //只取MD5码的一部分,这样恶意访问者无法知道取的是哪几位
                for (int i = 3; i < s.Length - 1; i++)
                {
                    //将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符
                    //进一步对生成的MD5码做一些改造
                    pwd = pwd + (s[i] < 198 ? s[i] + 28 : s[i]).ToString("X");
                }
                return pwd;
            }
            /// <summary>
            /// table转化为数组 
            /// </summary>
            /// <param name="table"> datatable对象</param>
            /// <param name="status">M,只查一条数据,否则查多条</param>
            /// <returns></returns>
            public  List<Dictionary<string, object>> QueryData(DataTable table, string status)
            {
                List<Dictionary<string, object>> outdata = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<Dictionary<string, object>> listdata = new List<Dictionary<string, object>>();
                try
                {
                    DataTable tb = new DataTable();
                    tb = table;
                    //如果数据库返回的总数据量少于一页显示的量,则循环次数为返回的数据量,反之就是规定的一页数据量
                    //strip 具体拿取 的信息条数          
                    if (tb.Rows.Count > 0)
                    {
                        if (status.Equals("M"))
                        {
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                //重置参数
                                listdata = new List<Dictionary<string, object>>();
                                dic = new Dictionary<string, object>();

                                for (int j = 0; j < tb.Columns.Count; j++)
                                {
                                    dic.Add(tb.Columns[j].ColumnName, tb.Rows[i][j].ToString());

                                }
                                outdata.Add(dic);
                            }
                        }
                        else
                        {
                            //每查询一次就存入一次Outdata中    i是行数,c是列数
                            for (int i = 0; i < 1; i++)
                            {

                                dic = new Dictionary<string, object>();
                                for (int c = 0; c < tb.Columns.Count; c++)
                                {
                                    dic.Add(tb.Columns[c].ColumnName, tb.Rows[i][c].ToString());
                                }
                                outdata.Add(dic);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {

                }
                return outdata;
            }
            /// <summary>
            /// SqlDataReader转化为Table
            /// </summary>
            /// <param name="reader">SqlDataReader对象</param>
            /// <returns></returns>
            public  DataTable ConvertDataReaderToDataTable(SqlDataReader reader)
            {
                try
                {
                    DataTable objDataTable = new DataTable();
                    int intFieldCount = reader.FieldCount;
                    for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
                    {
                        objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
                    }
                    objDataTable.BeginLoadData();

                    object[] objValues = new object[intFieldCount];
                    while (reader.Read())
                    {
                        reader.GetValues(objValues);
                        objDataTable.LoadDataRow(objValues, true);
                    }
                    reader.Close();
                    objDataTable.EndLoadData();

                    return objDataTable;

                }
                catch (Exception ex)
                {
                    throw new Exception("转换出错!", ex);
                }

            }

            /// <summary>
            /// SQL 语句查询转化为数组 
            /// </summary>
            /// <param name="cmdstr"> SQL语句</param>
            /// <param name="status">M,查多条数据,否则1条</param>
            /// <returns></returns>
            public  List<Dictionary<string, object>> QueryDataSQL(string cmdstr, string status)
            {
                List<Dictionary<string, object>> outdata = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<Dictionary<string, object>> listdata = new List<Dictionary<string, object>>();
                SqlConnection con = new SqlConnection(strcon);
                SqlDataAdapter da = new SqlDataAdapter(cmdstr, con);
                try
                {
                    con.Open();
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DataTable tb = new DataTable();
                    tb = ds.Tables[0];
                    //如果数据库返回的总数据量少于一页显示的量,则循环次数为返回的数据量,反之就是规定的一页数据量
                    //strip 具体拿取 的信息条数          
                    if (tb.Rows.Count > 0)
                    {
                        if (status.Equals("M"))
                        {
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                //重置参数
                                listdata = new List<Dictionary<string, object>>();
                                dic = new Dictionary<string, object>();

                                for (int j = 0; j < tb.Columns.Count; j++)
                                {
                                    dic.Add(tb.Columns[j].ColumnName, tb.Rows[i][j].ToString());
                                }
                                outdata.Add(dic);
                            }
                        }
                        else
                        {
                            //每查询一次就存入一次Outdata中    i是行数,c是列数
                            for (int i = 0; i < 1; i++)
                            {

                                dic = new Dictionary<string, object>();
                                for (int c = 0; c < tb.Columns.Count; c++)
                                {
                                    dic.Add(tb.Columns[c].ColumnName, tb.Rows[i][c].ToString());
                                }
                                outdata.Add(dic);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    con.Close();
                    CreateInLog("SQL 语句 " + cmdstr + "执行错误!" + ex.Message);
                }
                finally
                {
                    con.Close();
                }
                return outdata;
            }
            /// <summary>
            /// SQL 语句查询转化为数组 
            /// </summary>
            /// <param name="strconn"> 自定义连接串</param>
            /// <param name="cmdstr"> SQL语句</param>
            /// <param name="status">M,查多条数据,否则1条</param>
            /// <returns></returns>
            public  List<Dictionary<string, object>> QueryDataSQL(string strconn, string cmdstr, string status)
            {
                List<Dictionary<string, object>> outdata = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<Dictionary<string, object>> listdata = new List<Dictionary<string, object>>();
                SqlConnection con = new SqlConnection(strconn);
                SqlDataAdapter da = new SqlDataAdapter(cmdstr, con);
                try
                {
                    con.Open();
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    DataTable tb = new DataTable();
                    tb = ds.Tables[0];
                    //如果数据库返回的总数据量少于一页显示的量,则循环次数为返回的数据量,反之就是规定的一页数据量
                    //strip 具体拿取 的信息条数          
                    if (tb.Rows.Count > 0)
                    {
                        if (status.Equals("M"))
                        {
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                //重置参数
                                listdata = new List<Dictionary<string, object>>();
                                dic = new Dictionary<string, object>();

                                for (int j = 0; j < tb.Columns.Count; j++)
                                {
                                    dic.Add(tb.Columns[j].ColumnName, tb.Rows[i][j].ToString());
                                }
                                outdata.Add(dic);
                            }
                        }
                        else
                        {
                            //每查询一次就存入一次Outdata中    i是行数,c是列数
                            for (int i = 0; i < 1; i++)
                            {

                                dic = new Dictionary<string, object>();
                                for (int c = 0; c < tb.Columns.Count; c++)
                                {
                                    dic.Add(tb.Columns[c].ColumnName, tb.Rows[i][c].ToString());
                                }
                                outdata.Add(dic);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    con.Close();
                    CreateInLog("SQL 语句 " + cmdstr + "在" + strconn + "执行错误!" + ex.Message);
                }
                finally
                {
                    con.Close();
                }
                return outdata;
            }
            /// <summary>
            /// SQL 执行本地查询存储过程转化为数组 
            /// </summary>
            /// <param name="cmdstr"> SQL语句</param>
            /// <param name="status">M,查多条数据,否则1条</param>
            /// <returns></returns>
            public  List<Dictionary<string, object>> QueryDataParameter(string storedProcName, SqlParameter[] parameters, string status)
            {
                List<Dictionary<string, object>> outdata = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<Dictionary<string, object>> listdata = new List<Dictionary<string, object>>();
                //DataTable dataTable2 = new DataTable();

                try
                {
                    DataTable dataTable2 = SqlQueryParameter(storedProcName, parameters);
                    DataTable tb = new DataTable();
                    tb = dataTable2;
                    //如果数据库返回的总数据量少于一页显示的量,则循环次数为返回的数据量,反之就是规定的一页数据量
                    //strip 具体拿取 的信息条数          
                    if (tb.Rows.Count > 0)
                    {
                        if (status.Equals("M"))
                        {
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                //重置参数
                                listdata = new List<Dictionary<string, object>>();
                                dic = new Dictionary<string, object>();

                                for (int j = 0; j < tb.Columns.Count; j++)
                                {
                                 
                                    dic.Add(tb.Columns[j].ColumnName, tb.Rows[i][j].ToString());

                                }
                                outdata.Add(dic);
                            }
                        }
                        else
                        {
                            //每查询一次就存入一次Outdata中    i是行数,c是列数
                            for (int i = 0; i < 1; i++)
                            {

                                dic = new Dictionary<string, object>();
                                for (int c = 0; c < tb.Columns.Count; c++)
                                {
                                    
                                    dic.Add(tb.Columns[c].ColumnName, tb.Rows[i][c].ToString());
                                    

                                }
                                outdata.Add(dic);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CreateInLog("SQL 存储过程 " + storedProcName + "执行错误!" + ex.Message);
                }
                finally
                {

                }
                return outdata;
            }
            /// <summary>
            /// SQL 执行非本地查询存储过程转化为数组 
            /// </summary>
            /// <param name="strconn"> 自定义连接串</param>
            /// <param name="cmdstr"> SQL语句</param>
            /// <param name="status">M,查多条数据,否则1条</param>
            /// <returns></returns>
            public  List<Dictionary<string, object>> QueryDataParameter(string strconn, string storedProcName, SqlParameter[] parameters, string status)
            {
                List<Dictionary<string, object>> outdata = new List<Dictionary<string, object>>();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                List<Dictionary<string, object>> listdata = new List<Dictionary<string, object>>();
                //DataTable dataTable2 = new DataTable();

                try
                {
                    DataTable dataTable2 = SqlQueryParameter(strconn, storedProcName, parameters);
                    DataTable tb = new DataTable();
                    tb = dataTable2;
                    //如果数据库返回的总数据量少于一页显示的量,则循环次数为返回的数据量,反之就是规定的一页数据量
                    //strip 具体拿取 的信息条数          
                    if (tb.Rows.Count > 0)
                    {
                        if (status.Equals("M"))
                        {
                            for (int i = 0; i < tb.Rows.Count; i++)
                            {
                                //重置参数
                                listdata = new List<Dictionary<string, object>>();
                                dic = new Dictionary<string, object>();

                                for (int j = 0; j < tb.Columns.Count; j++)
                                {
                                    dic.Add(tb.Columns[j].ColumnName, tb.Rows[i][j].ToString());

                                }
                                outdata.Add(dic);
                            }
                        }
                        else
                        {
                            //每查询一次就存入一次Outdata中    i是行数,c是列数
                            for (int i = 0; i < 1; i++)
                            {

                                dic = new Dictionary<string, object>();
                                for (int c = 0; c < tb.Columns.Count; c++)
                                {
                                    
                                    dic.Add(tb.Columns[c].ColumnName, tb.Rows[i][c].ToString());
                                    

                                }
                                outdata.Add(dic);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CreateInLog("SQL 存储过程 " + storedProcName + "执行错误!" + ex.Message);
                }
                finally
                {

                }
                return outdata;
            }
        #endregion
View Code

 

public static string SqlHost = GetConfig.GetConfiguration("ConnectionStrings:SqlHost");//获取配置的服务器
public static string SqlAdminName = GetConfig.GetConfiguration("ConnectionStrings:SqlAdminName");//数据库账号
public static string SqlAdminPswd = GetConfig.GetConfiguration("ConnectionStrings:SqlAdminPswd");//数据库密码
public static string SqlCatalogProFix = GetConfig.GetConfiguration("ConnectionStrings:SqlCatalogProFix");//数据库
public static string strcon = string.Format(@"Data Source={0};User ID={1};Password={2};Initial Catalog={3};Pooling=true", SqlHost, SqlAdminName, SqlAdminPswd, SqlCatalogProFix); ConnectionStrings appsettings文件配置的数据库连接串 GetConfiguration//获取配置的数据库连接信息 也可以使用依赖注入调用

 

        public static string GetConfiguration(string configKey)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
            var config = builder.Build();
            if (configKey.Contains(":"))
            {
                return config.GetSection(configKey).Value;//获取分级参数值
            }
            else
            {
                return config[configKey];//获取直级参数值
            }
            //youdianwenti w xiangxiang
        }
View Code

如有侵权,请联系作者,将进行整改

 今日分享结束

能帮朋友解决问题的记得给个关注支持一下,以后将多多分享SQL SERVER 相关知识

标签:SQLHelp,string,C#,List,SOL,dic,int,new,tb
From: https://www.cnblogs.com/libo962464/p/16758269.html

相关文章

  • 条件期望:Conditional Expectation 举例详解之入门之入门之草履虫都说听懂了
    我知道有很多人理解不了“条件期望”(ConditionalExpectation)这个东西,有的时候没看清把随机变量看成事件,把\(\sigma\)-algebra看成随机变量从而思路全错的时候,我也......
  • java static 静态
    static是java语言中的关键字,意思是“静态的”,它可以用来修饰变量、方法、代码块等,修饰的变量叫做静态变量,修饰的方法叫做静态方法,修饰的代码块叫做静态代码块。static的......
  • torch.utils.data.Dataset和torch.utils.data.TensorDataset
    首先我们先看一下Dataset的官方api:CLASStorch.utils.data.Dataset(*args,**kwds)AnabstractclassrepresentingaDataset. Alldatasetsthatrepresentama......
  • C语言下for循环的一点技巧总结
    for循环是普遍应用与各种计算机语言的一种循环方式。一般情况下,for循环规则:for(条件一;条件二;条件三)条件一为满足条件,也就是条件一为1时,进入这个for循环。条件二为循环......
  • 关于windows-Server-下服务Service的卸载方法
    关于windows中的service的卸载,一般有如下3种方法这里笔者以卸载MySQL服务为例,删除其他service方法也都是一样的无论那种方法,我们首先应该先停止服务,再卸载,可以通过服务管......
  • 第二组chap1-2学习总结
      在两周C语言的学习课程中,让我们从认识C语言历史到开始动手打代码,从最初对C语言的懵懵懂懂到小有成就,我们对C语言的认识和运用也越来越深。充实着我们的不仅仅是学习......
  • quicklib json序列
    quicklibjson序列quicklib面向MODEL的JSON序列。unitUnit2;///<author>cxg2022-6-14</author>interfaceusesquick.Json.Serializer,Quick.MemoryCache.Seri......
  • 「前端料包」深入理解JavaScript原型和原型链
    1.前言关于JS原型和原型链我之前刚学js就有写过一篇学习笔记形式的博客,但前两天翻出来一看——什么鬼,这是我写的吗?自己都看不懂了,于是我重新整理思路,今天「前端料包」......
  • CF1415D XOR-gun 题解 二分答案/贪心
    题目链接https://codeforces.com/problemset/problem/1415/D题目大意给定一个长为\(n\)的不降序列,每次操作可以任选相邻的两个数,并将这两个数替换为两个数按位异或的......
  • 「前端料包」一文吃透盒子模型BFC
    前言接触写博客有一段时间了,都是边学边学着写,但总感觉写的凌乱,想起啥写啥。这几天在刷红宝书,收获还是蛮多的,决定结合自己的学习,写一个系列,我叫它「前端料包」,旨在巩固前......