PRivate void Button_Click(object sender, RoutedEventArgs e) { //ADO.NET 連接方式查詢數據庫 ExcuteReader執行查詢 //1.創建連接對象 using (SqlConnection conn = new SqlConnection(SQLHelper.ConnectionString)) { //2.創建命令對象 using (SqlCommand scmd = new SqlCommand()) { //3.打開鏈接 conn.Open(); //4. 發送命令 scmd.CommandText = "select * from Student"; scmd.CommandType = CommandType.Text; scmd.Connection = conn; //執行命令 using (SqlDataReader reader = scmd.ExecuteReader()) { //5.處理數據 while (reader.Read()) { string name = reader["s_Name"].ToString(); int age = Convert.ToInt32(reader.GetValue(reader.GetOrdinal("s_Age"))); MessageBox.Show(string.Format("name={0}, age={1}", name, age)); } //6.關閉連接 //備注:因為這里使用了using代碼塊,會自動進行資源回收。就不用手動關閉連接了。datareader讀取的結果集,還是存放在數據庫中。 } } } }
注意:步驟2,和步驟3可以互換位置,只要在執行操作之前,連接打開就行!
新聞熱點
疑難解答