您好,登錄后才能下訂單哦!
本篇文章為大家展示了C#中怎么利用OleDbDataReader讀取數據,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
查詢得到OleDbDataReader后,有三種方式支持數據讀取,如下:
//方法一**速度中等OleDbDataReader reader = command.ExecuteReader();while (reader.Read()){ var t1 = reader[0]; }//方法二**速度最慢OleDbDataReader reader = command.ExecuteReader();while (reader.Read()){ var t1 = reader["字段名"]; }//方法三**速度最快OleDbDataReader reader = command.ExecuteReader();while (reader.Read()){ var t1 = reader.GetValue(0); }
關于速度的描述,下面我們來簡單驗證一下。
有一個數據庫,數據庫中的表TEST有105945行數據,設計一個循環讀取來測試他們的讀取速度。
測試源碼如下:
static void Main(string[] args) { string connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source={0};", "F:\\2.mdb"); string s1 = "ID"; string s2 = "探測號"; string s3 = "X"; string s4 = "Y"; string s5 = "H"; string sql = string.Format("SELECT {0},{1},{2},{3},{4} FROM 管點表", s1, s2, s3, s4, s5); TimeSpan time1 = new TimeSpan(); TimeSpan time2 = new TimeSpan(); TimeSpan time3 = new TimeSpan(); int count = 50; //數據庫中查詢的表有105945行 for (int i = 0; i < count; i++) { using (OleDbConnection conn = new OleDbConnection(connstr)) { #region conn.Open(); OleDbCommand command = conn.CreateCommand(); command.CommandText = sql; OleDbDataReader reader = command.ExecuteReader(); DateTime now = DateTime.Now; while (reader.Read()) { var t1 = reader[0]; var t2 = reader[1]; var t3 = reader[2]; var t4 = reader[3]; var t5 = reader[4]; } time1 = time1 + (DateTime.Now - now); #endregion } } for (int i = 0; i < count; i++) { using (OleDbConnection conn = new OleDbConnection(connstr)) { #region conn.Open(); OleDbCommand command2 = conn.CreateCommand(); command2.CommandText = sql; OleDbDataReader reader = command2.ExecuteReader(); DateTime now = DateTime.Now; while (reader.Read()) { var t1 = reader[s1]; var t2 = reader[s2]; var t3 = reader[s3]; var t4 = reader[s4]; var t5 = reader[s5]; } time2 = time2 + (DateTime.Now - now); #endregion } } for (int i = 0; i < count; i++) { using (OleDbConnection conn = new OleDbConnection(connstr)) { #region conn.Open(); OleDbCommand command3 = conn.CreateCommand(); command3.CommandText = sql; OleDbDataReader reader = command3.ExecuteReader(); DateTime now = DateTime.Now; while (reader.Read()) { var t1 = reader.GetValue(0); var t2 = reader.GetValue(1); var t3 = reader.GetValue(2); var t4 = reader.GetValue(3); var t5 = reader.GetValue(4); } time3 = time3 + (DateTime.Now - now); #endregion } } Console.WriteLine(string.Format("方法一:\r\n耗時:{0}s", time1.TotalSeconds)); Console.WriteLine(string.Format("方法二:\r\n耗時:{0}s", time2.TotalSeconds)); Console.WriteLine(string.Format("方法三:\r\n耗時:{0}s", time3.TotalSeconds)); Console.ReadKey(); }
循環50次結果,即50*105945:
100次循環結果:,即100*105945:
上述內容就是C#中怎么利用OleDbDataReader讀取數據,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。