首页 >> 文档 >> C#专题

C#连接SQL Server数据库实例代码

发布日期:2008-07-07最近更新:2008-07-07来源:BHCODE作者:

以下是C#连接SQL Server数据库的实例代码:

using System;

using System.IO;

using System.Data.SqlClient;

 

namespace ConsoleSqlConnection

{

 /// <summary>

 /// Class1 的摘要说明。

 /// </summary>

 class SqlConnectionClass

 {

  /// <summary>

  /// 应用程序的主入口点。

  /// </summary>

  [STAThread]

  static void Main(string[] args)

  {

   string strCon = @"server=(local);Integrated Security=true;database=Northwind;uid=sa;pwd=sa";

   SqlConnection MyCon = new SqlConnection(strCon);

   // 打开SQL Server数据库

   try

   {

    MyCon.Open();

 

    // 浏览数据库

    string strSQL = @"select * from Customers";

    SqlCommand MyCommand = new SqlCommand(strSQL, MyCon);

 

    // 将检索结果放入SqlDataReader中

    SqlDataReader MyDataReader = MyCommand.ExecuteReader();

 

    Console.WriteLine("显示数据库中的数据");

    while (MyDataReader.Read())

    {

     Console.WriteLine("用户名称:{0} 公司名称:{1} 所在城市:{2}", MyDataReader["CustomerID"].ToString().PadRight(10), MyDataReader["CompanyName"].ToString().PadRight(25), MyDataReader["City"].ToString());

    }

    MyDataReader.Close();

   }

   catch (Exception ex)

   {

    Console.WriteLine("{0}", ex.ToString());

   }

   finally

   {

    // 使用完毕,关闭数据库

    MyCon.Close();

   }

   Console.ReadLine();

  }

 }

}

本周推荐
MORE
热点关注
MORE