zoukankan      html  css  js  c++  java
  • 将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();
             }
    
    
        }
  • 相关阅读:
    java使用递归删除非空目录
    关于Java日期的两道例题
    equals和==的区别
    从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序。
    输出所有的水仙花数
    99乘法表
    switch
    next()、nextInt()
    流程控制
    Scanner从键盘输入
  • 原文地址:https://www.cnblogs.com/yunquan/p/7363110.html
Copyright © 2011-2022 走看看