《使用SqlConnection类连接数据库方法》
//引入命名空间
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
//ConnectionString定义了连接字符串
string ConnectionString = "Data Source=. ; Initial Catalog=Pubs; User ID=sa";
//使用连接字符串构造一个SqlConnection实例
SqlConnection conn = new SqlConnection(ConnectionString);
try
{
//打开连接
conn.Open();
//如果当前状态打开,在控制台输出
if (conn.State == ConnectionState.Open)
{
Label1.Text = "当前数据库已经连接!<br/>";
Label1.Text += "连接字符串为:" + conn.ConnectionString;
}
}
catch (SqlException ex)
{
Label1.Text = "当前数据库已经失败!<br/>";
Label1.Text += "失败的原因是:" + ex.Message;
}
finally
{
//调用Close方法即使关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
《使用SqlConnectionStringBuilder连接字符串方法》
//引入命名空间
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnectionStringBuilder connBuider = new SqlConnectionStringBuilder();
//DataSource表示数据源位置,可以是IP地址,也可以指定一个DNS名称
connBuider.DataSource = ".";
//InitialCataLog指定需要连接数据库的名称
connBuider.InitialCatalog = "Pubs";
//IntegratedSecurity表示是否使用整合身份验证进行登录数据库
connBuider.IntegratedSecurity = false;
//不使用整合Windows身份验证时,指定用户ID和密码
connBuider.UserID = "sa";
connBuider.Password = "";
//使用SqlConnetionStringBuilder.ToString()方法将会输出连接字符串
using(SqlConnection conn=new SqlConnection(connBuider.ToString()))
try
{
//打开连接
conn.Open();
//如果当前状态打开,在控制台输出
if (conn.State == ConnectionState.Open)
{
Label1.Text = "当前数据库已经连接!<br/>";
Label1.Text += "连接字符串为:" + conn.ConnectionString;
}
}
catch (SqlException ex)
{
Label1.Text = "当前数据库已经失败!<br/>";
Label1.Text += "失败的原因是:" + ex.Message;
}
finally
{
//调用Close方法即使关闭连接
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}