第十五章 SqlDataReader reader = comm.ExecuteReader(); while (reader.Read())

qq_36074233發表於2016-11-30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;


namespace ConsoleApplication1
{
    class Program
    {
        public void GetStudentList()
        {
            string strConn = @"Data Source=.;Initial Catalog=MySchool;Integrated Security=True";
            SqlConnection conn = new SqlConnection(strConn);
            try
            {
                conn.Open();
                Console.WriteLine("資料庫開啟");
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("select");
                sb.AppendLine("                *");
                //sb.AppendLine("                studentno");
                //sb.AppendLine("                ,studentname");
                sb.AppendLine("from");
                sb.AppendLine("           student");

                Console.WriteLine(sb.ToString());
                SqlCommand comm = new SqlCommand(sb.ToString(), conn);
                int i = (int)comm.ExecuteScalar();
                SqlDataReader reader = comm.ExecuteReader();
                while (reader.Read())
                {
                    //--他(1)
                    Console.WriteLine(reader["studentno"]);
                    Console.WriteLine(reader["studentname"]);
   //---------------------- Console.ReadLine(); 有這句話會卡住,敲一個回車輸出一個學號和姓名
                    //或(2)--Console.WriteLine(reader[0]);
                    //--Console.WriteLine(reader[1]);
                    //或(3)--Console.WriteLine(reader[0]+"   "+reader[2]);

                }
            }
            catch (Exception)
            {

                Console.WriteLine("資料庫操作失敗!");
            }
            finally
            {
                conn.Close();
                Console.WriteLine("資料庫關閉");
            }

        }
        static void Main(string[] args)
        {
            Program pro = new Program();
            pro.GetStudentList();
            Console.ReadLine();
        }
    }
}

相關文章