讀取student表中的資料列印到螢幕,代碼
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 string sqlc = @"server=.\sqlexpress;database=MyDataBase15_31;uid=sa;pwd=sa"; 6 using (SqlConnection sqlconn = new SqlConnection(sqlc)) 7 { 8 string sql = @" select * from student "; 9 using (SqlCommand sqlcom = new SqlCommand(sql))10 {11 if (sqlconn.State == ConnectionState.Closed) //ConnectionState 枚舉 描述與資料來源的串連的目前狀態。12 { //State 指示 SqlConnection 的狀態。 13 14 sqlconn.Open();15 //Console.WriteLine("成功");16 }17 SqlDataReader reader = sqlcom.ExecuteReader();//若要建立 SqlDataReader,必須調用 SqlCommand 對象的 ExecuteReader 方法,而不要直接使用建構函式。18 using (reader)19 {20 if (reader.HasRows)21 {22 //if (reader.Read())23 while(reader.Read())24 {25 Console.WriteLine("{0}{1}{2}{3}{4}",26 reader["sId"],27 reader["sName"],28 reader["sAge"],29 reader["sGender"],30 reader["sClass"]31 );32 }33 34 }35 }36 }37 38 }39 40 }41 }
F6產生成功,F5報異常:ExecuteReader: Connection 屬性尚未初始化。
問題分析:看到Connection,想到資料庫連接失敗,通過//Console.WriteLine("成功");排除錯誤,仔細驗證SQL語句,沒有問題,百度了一下有說代碼中多次調用DataReader的函數,可能是因為開啟太多的連結,但是檢查後還是沒有發現問題,這時突然看到問題所在:
using (SqlCommand sqlcom = new SqlCommand(sql))
SqlCommand()缺少參數,真是大意,改正後
using (SqlCommand sqlcom = new SqlCommand(sql,sqlconn))
順利通過。