Process the Results of a SQL Query Using a Data Reader - CSharp Database

CSharp examples for Database:SQL Command

Description

Process the Results of a SQL Query Using a Data Reader

Demo Code


using System;/*from   ww w  .ja v  a  2  s  .c  o m*/
using System.Data;
using System.Data.SqlClient;

class MainClass
    {
        public static void Main()
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = @"Data Source = .\sqlexpress;" +
                    "Database = Northwind; Integrated Security=SSPI";

                using (SqlCommand com = con.CreateCommand())
                {
                    com.CommandType = CommandType.Text;
                    com.CommandText = "SELECT BirthDate,FirstName,LastName FROM "+
                        "Employees ORDER BY BirthDate;SELECT * FROM Employees";

                    con.Open();

                    using (SqlDataReader reader = com.ExecuteReader())
                    {
                        Console.WriteLine("Employee Birthdays (By Age).");

                        while (reader.Read())
                        {
                            Console.WriteLine("  {0,18:D} - {1} {2}",
                                reader.GetDateTime(0),  // Retrieve typed data
                                reader["FirstName"],    // Use string index
                                reader[2]);             // Use ordinal index
                        }
                        Console.WriteLine(Environment.NewLine);

                        reader.NextResult();
                        Console.WriteLine("Employee Table Metadata.");
                        for (int field = 0; field < reader.FieldCount; field++)
                        {
                            Console.WriteLine("  Column Name:{0}  Type:{1}",
                                reader.GetName(field),
                                reader.GetDataTypeName(field));
                        }
                    }
                }
            }

        }
    }

Result


Related Tutorials