将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();
         }


    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值