使用VS2015自带的 (localdb)\MSSQLLocalDB 或者 (localdb)\ProjectsV13,这是mini版的数据库系统,大概几十兆大小,在连接字符串中,它俩作为服务器的名字和默认实例。
连接字符串:
string constr = "server=(localdb)\\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=true;";
string constr = "Data Source=(localdb)\\MSSQLLocalDB;database=Test;Integrated Security=sspi;";
server等价于Data Source,指定服务器;
Initial Catalog等价于database:指定哪一个数据库
Integrated Security是Windows登陆验证方式,=true或者=SSPI是等价的
如果我们放置一个按钮button1,点击按钮就连接数据库的话,则在按钮的点击事件中有:
Windows 身份验证模式:Integrated Security=true
private void button1_Click(object sender, EventArgs e)
{
try
{
//string constr = "server=(localdb)\\MSSQLLocalDB;Initial Catalog=Test;Integrated Security=true";
string constr = "Data Source=(localdb)\\MSSQLLocalDB;database=Test;Integrated Security=true";
SqlConnection conn = new SqlConnection(constr);//1、创建连接对象conn
conn.Open(); //2、打开方法
if (conn.State == ConnectionState.Open) // 通过state字段判断是否连接成功
{
label1.Text = "数据库打开成功";
}
conn.Close();
if(conn.State==ConnectionState.Closed)
{
label2.Text = "数据库关闭成功"; ;
}
}
catch //通过异常来处理打不开数据库的情况
{
MessageBox.Show("数据库打开失败");
}
}
SQL Server方式登录:uid=sa;pwd=
user id 或者password
右键(localdb)\MSSQLLocalDB 新建如下查询,可设置sa用户生效,sa是超级管理员:super administrator
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '' ;
GO
private void button1_Click(object sender, EventArgs e)
{
try
{
string constr = "Data Source=(localdb)\\MSSQLLocalDB;database=Test;uid=sa;pwd=";
SqlConnection conn = new SqlConnection(