• 将Sql查询语句获取的数据插入到List列表里面


      Sql查询语句获取的数据是分格式的,我们还用SqlDataReader来做,然后用IDataReader来接收读取,以下是代码:

    //我想查询一个用户表的信息,该用户有姓名,密码,信息三列
    //1.定义一个用户类型的List数组,userInfo类的代码在下方
     List<userInfo> userInfo = new List<userInfo>();
    
    
    //2.我们要读取查询语句的数据,并且保存了。这里我们将使用IDataReader语句
    //数据库类的实例,类的代码在下方
    DB db = new DB();
    
    //解析方法
                    using(IDataReader read=db.read("select * from userInfo"))
                    {
                        while (read.Read())
                        {
                            userInfo a = new userInfo();
                            a.user_Name = read[0].ToString();
                            a.user_Passwd = read[1].ToString();
                            a.user_region = read[2].ToString();
                            userInfo.Add(a);
                        }                   
                    }
     

    userInfo类的代码:

        public class userInfo
        {      
    
            public string user_Name{get;set;}
            public string user_Passwd {get;set;}
            public string user_region{get;set;}
        }

    DB类的代码:

        public  class DB
        {
       
             //数据库操作
             //1.连接数据库
             public  SqlConnection connect()
             {
            
                 string rode = @"Data Source=KTY;Integrated Security=SSPI;Initial Catalog=shuyunquan";
    
                 SqlConnection con = new SqlConnection(rode);
                 con.Open();
                 return con;
             }
              //执行语句的数据库方法
             public  SqlCommand command(string sql)
             {
    
                 SqlCommand cmd = new SqlCommand(sql, connect());
                 return cmd;
    
             }
              //行数影响的方法
             public  int Execute(string sql)
             {
                 return command(sql).ExecuteNonQuery();
    
             }
              //返回查询结果的方法
             public SqlDataReader read(string sql)
             {
                 return command(sql).ExecuteReader();
             }
    
    
        }
  • 相关阅读:
    利用npm 安装删除模块
    C#比较类/接口、Dictionary 排序
    关于二叉树的一些基本知识
    关于前端JS的一些常用方法和知识
    组装Json数据的一种简单办法(不用Stringbuilder方法)
    windows环境下Kubernetes及Docker安装(那些坑)
    七夕给自己的礼物-上线排盘小程序
    Asp.net 自定义CustomerSession 存放到Redis中
    CodeTimer 代码性能计数器
    我虽码农,亦不搬砖
  • 原文地址:https://www.cnblogs.com/yunquan/p/7363110.html
Copyright © 2020-2023  润新知