using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace Northwind { class Program { static void Main(string[] args) { //创建连接对象,使用集成安全方式连接,更安全 SqlConnection sqlConn = new SqlConnection(@"data source=localhost; Integrated Security=SSPI;Initial Catalog=northwind"); //创建命令对象 SqlCommand sqlCmd = new SqlCommand( "Select CategoryID, CategoryName from Categories", sqlConn); //打开数据库 sqlConn.Open(); //执行查询,并将结果集返回给sqlDataReader SqlDataReader sqlDataReader = sqlCmd.ExecuteReader(); //遍历所有的行,直到结束 while (sqlDataReader.Read()) { Console.WriteLine("{0}\t{1}", sqlDataReader.GetInt32(0), sqlDataReader.GetString(1)); } Console.ReadLine(); //关闭sqlDataReader对象 sqlDataReader.Close(); //断开连接 sqlConn.Close(); } } }