星空网 > 软件开发 > ASP.net

怎样在C#中从数据库中读取数据(数据读取器)

实现在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中的代码,否则不执行

            {

                Console.WriteLine("网络异常!");

            }

            finally //无论如何都会执行finally中的代码

            {

                if(con!=null) //判断con不为空

                {

                    con.Close();

                }
            }




原标题:怎样在C#中从数据库中读取数据(数据读取器)

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流