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

时间:2023-03-09 05:45:01
怎样在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();

}
            }

相关文章