c#怎么连接sql server数据库

2024-11-20 12:45:55
推荐回答(1个)
回答(1):

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

namespace SQLServerConnection
{
class Program
{
static void Main(string[] args)
{
//默认实例
//string connectionString = "Data Source=SERVER_NAME;Initial Catalog=AdventureWorks2008R2;User ID=sa;Password=sa12345";
//命名实例
string connectionString = "Data Source=SERVER_NAME\\SQL2012;Initial Catalog=AdventureWorks2012;User Id=sa;Password=sa12345";

// Assumes connectionString is a valid connection string.
using (SqlConnection connection = new SqlConnection(connectionString))
{
//打开连接
connection.Open();
// Do work here.
SqlCommand sqlcmd = connection.CreateCommand();
//sqlcmd.CommandText = "select top 10 * from Person.Person;";

sqlcmd.CommandText = "select top 10 * from Person;";

SqlDataReader sqlreader = sqlcmd.ExecuteReader();
while (sqlreader.Read())
{
Console.WriteLine("\t{0}\t{1}",sqlreader["firstname"],sqlreader["lastname"]);
}
sqlreader.Close();
connection.Close();//因为使用了using,所以这一条语句可以不写,因为当离开using代码块以后,connection自动关闭
}
}
}
}