天天看點

使用SQL資料提供程式通路MSSQL資料庫

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace SqlServerProvider
{
    class Program
    {
        static void Main(string[] args)
        {
            string connString = @"server=snh;integrated security =true;database =northwind";
            string sql = @"select * from employees";
            SqlConnection conn = null;
            SqlDataReader reader = null;
            try
            {
                conn = new SqlConnection(connString);
                conn.Open();

                SqlCommand cmd = new SqlCommand(sql, conn);
                reader = cmd.ExecuteReader();

                Console.WriteLine("This program demonstrates the use of " + "the SQL Server Data Provider.");
                Console.WriteLine("Querying database {0} with query {1}\n", conn.Database, cmd.CommandText);
                Console.WriteLine("First Name\tLast Name\n");
                while (reader.Read())
                {
                    Console.WriteLine("{0} | {1}", reader["FirstName"].ToString().PadLeft(10), reader[1].ToString().PadLeft(10));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e);
            }
            finally
            {
                reader.Close();
                conn.Close();
            }
            Console.ReadKey();
        }
    }
}