使用ExecuteReader讀取多行多列的數據

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;數據庫

namespace ADO.NET詳解
{
    class Program
    {
        static void Main(string[] args)
        {ide

      using (SqlConnection conn = new SqlConnection(@"Data Source=.;Database=Database1;user ID=sa;pwd=888888"))//在Sqlconnection,Sqlcommand,SqlDataReader等使用using,能夠
            //釋放掉所佔用的資源,至關於Disposed()方法.
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from T_Users";
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        Console.WriteLine("數據庫中有如下用戶名:");
                        while (reader.Read()) //循環讀取數據庫中的數據,直到最後一條記錄的最後
                        { 
                                                      //這裏須要指定某列的序號
                            //Console.WriteLine(reader.GetString(1));spa

                            //而使用下列的方法GetOrdinal能夠直接指定某列的名稱,而不用把列序號寫死在程序裏,跟以上效果同樣
                            Console.WriteLine(reader.GetString(reader.GetOrdinal("username")));
                        }
                    }blog

                }
                Console.ReadKey();
            }
        }
    }
}資源

 運行效果:get

數據庫數據:cmd

相關文章
相關標籤/搜索