1. 程式人生 > >資料獲取的兩種方法:DataList和SqlDataReader

資料獲取的兩種方法:DataList和SqlDataReader

資料獲取的兩種方法:一種是DataReader向後讀寫的類,缺點是不夠靈活; 另一種是DataSet資料集,會消耗一些額外的記憶體,但是靈活性高

string strsql = "Data Source=Thomas-PC;Initial Catalog=Book;Integrated Security=True";
        SqlConnection conn = new SqlConnection(strsql);
        try{
            Label1.Text = "資料庫連結成功";
            conn.Open();
            string sqlQuery = "select * from users";
            SqlCommand cmd = new SqlCommand(sqlQuery,conn);
            SqlDataReader sqr = cmd.ExecuteReader();  //DataReader向後讀寫的類,不夠靈活
            while (sqr.Read())
            	Response.Write(sqr["author"]+"<br/>");
            /*SqlDataAdapter sda = new SqlDataAdapter(sqlQuery,conn);
            DataSet ds = new DataSet();           //DataSet資料集會消耗一些額外的記憶體,靈活性高
            int numbers = sda.Fill(ds,"Tables");
            for(int i = 0; i < numbers; i++)
            	Response.Write(ds.Tables["Tables"].Rows[i]["id"].ToString()+"<br/>");
            string deleteQuery = "delete from users where id = 1";
            SqlCommand sqlcommand = new SqlCommand(deleteQuery,conn);
            sqlcommand.ExecuteNonQuery();
            */
            Label1.Text = "資料刪除成功";
        }
        catch (Exception ee){
            Label1.Text = ee.ToString();
        }