c#中连接SQL Server数据库

来源:互联网 发布:qq三国js技能满级 编辑:程序博客网 时间:2024/06/05 04:05
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();}}}
原创粉丝点击