20101014 学习记录:DataReader ←→ DataTable

时间:2021-11-23 00:12:05


ExecuteReader 返回 一个IDataReader对像,其性能最高。其它的组件返回datatable或dataset其实内部都是通过ExecuteReader 读取数据填充的


只取一条,可以这么写
SqlConnection con = new SqlConnection(.........);
SqlCommand cmd=new SqlCommand(select * form tb1 where id=2);
con.Open();
DataTable dt = new DataTable();
SqlDataReader dr = cmd.ExecuteReader();

if(dr.Read()){
    --dr["field"]
    //可以写到数datatable,或自己定义的类或其它
}

con.Close(); 

-----------------------------------------------------------------------  

SqlConnection con = new SqlConnection(.........);
SqlCommand cmd=new SqlCommand(select * form tb1 where id=2);
con.Open();
DataTable dt = new DataTable();
SqlDataAdapter mySDA = new SqlDataAdapter();
mySDA.SelectCommand = cmd;
mySDA.Fill(dt);
con.Close();

 

  strQuery = "Select....";
  SqlDataAdapter da = new SqlDataAdapter(strQuery, con);
  DataTable dt = new DataTable();
  da.Fill(dt);