2016年5月29日日曜日

[SQL Server]SqlDataReaderを使ってデータを取得


・App.config


  
    
  


・プログラム
using System;
using System.Configuration;
using System.Data.SqlClient;

namespace SqlServerTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            
            using(SqlConnection con = new SqlConnection(connectionString)){
                con.Open();

                using (SqlCommand command = con.CreateCommand())
                {
                    string sql = "SELECT TOP 10 [BusinessEntityID], [FirstName] " +
                                 "FROM [Person].[Person];";
                    command.CommandText = sql;

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            string[] data = new string[] { reader["BusinessEntityID"].ToString(), 
                                                          reader["FirstName"].ToString() };
                            Console.WriteLine(string.Join("\t", data));
                        }
                    }
                }
            }
        }
    }
}

0 件のコメント:

コメントを投稿