首页 > 代码库 > 连接sqlserver
连接sqlserver
using System;
using System.Data;
using System.Data.SqlClient;
namespace DBUtil
{
class Program
{
static void Main(string[] args)
{
//连接数据库
/**
* 注意如果是本地数据库用Trusted_Connection=SSPI;
* 是server的话用uid,pwd等账户密码进行验证
*/
SqlConnection myCon = new SqlConnection();
myCon.ConnectionString = @"Data Source=localhost\SQLEXPRESS;Initial Catalog=test;Trusted_Connection=SSPI";
try
{
//打开数据库
myCon.Open();
//使用SqlCommand提交查询命令
SqlCommand sql = new SqlCommand("select * from Student", myCon);
//获取数据适配器
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = sql;
//填充DataSet
DataSet ds = new DataSet();
sda.Fill(ds, "Student");
Console.WriteLine("{0}", ds.GetXml());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
myCon.Close();
}
}
}
}