设为首页 加入收藏

TOP

怎样在C#中从数据库中读取数据(数据读取器)(一)
2019-09-03 02:35:12 】 浏览:31
Tags:怎样 数据库 读取 数据

实现在C#中通过语句,查询数据库中的数据

      SqlConnection con = null; //创建SqlConnection 的对象

            try    //try里面放可能出现错误的代码
              {

                   string str = "data source=.;initial catalog=数据库名称;user ID=登录名;pwd=密码;";

                con = new SqlConnection(str);

                con.Open(); //打开数据库
 
          //以上操作为登录数据库的操作

                string sql = "select 列名1,列名2,列名3,列名4,列名5 from QQuser where 查询条件;

                SqlCommand com = new SqlCommand(sql,con);

                SqlDataReader read=com.ExecuteReader();  //用com(变量名)点上ExecuteReader()方法,该方法的类型是SqlDataReader类型

                while (read.Read()) //变量名点上Read()方法. 用循环来保证能将数据库中的数据全部读取完毕
                        //如果数据库中当前指针的下一行有数据则Read()方法返回true,如果没有数据则返回false
                {

                    int number = Convert.ToInt32(read["列名1"]);//查询列名1的数据,方法为: read(变量名)["列名"]; 该方法返回的是object类型

                    string name = read["列名2"].ToString(); //如上

                    string revise = read["列名3"].ToString();

                    string Email = read["列名4"].ToString();

                    int day = Convert.ToInt32(read["列名5"]);

                    Console.WriteLine("{0}\t{1}\t{2}\t\t{3}\t\t{4}", number, name, revise,Email,day);

                }
            }
            catch (Exception) //当try中有错误则执行catch中的代码,否则不执行

            {

    

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇阿里云系列——1.域名创建(详细.. 下一篇阿里云系列——4.网站备案后续(..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目