ExecuteReader: Connection 屬性尚未初始化。錯誤解決

來源:互聯網
上載者:User

讀取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))

順利通過。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.