代碼詳解C#中SQL連接字串的功能
來源:互聯網
上載者:User
using System.Data.SqlClient;
public class sqlServerConnection {
//
public static void Main() {
//下面就是標準的串連,注意SERVER是我的電腦名稱。SQLEXPRESS是資料庫執行個體。SSPI表示使用Windows登陸的帳戶。master是要串連的資料庫。
//
string cstr = "server=SERVER\\SQLEXPRESS;Initial Catalog=master;Integrated Security=SSPI";
//
try {
//
using (SqlConnection con = new SqlConnection(cstr)) {
con.Open();
System.Console.WriteLine("ServerVersion:{0}",con.ServerVersion);
System.Console.WriteLine("State:{0}",con.State);
}
//
}
catch (System.Exception sqle) {
System.Console.WriteLine(sqle.Message);
}
//
}
//
}
/*
程式的輸出:
ServerVersion:09.00.3042
State:Open
*/
//不使用遠端連線的時候應該把C#中SQL連接字串改為:
"Server=localhost\\SQLExpress;Integrated Security=SSPI"
//也可以指定預設的資料庫,例如,指定預設資料庫是"master"就應該寫為:
"Server=localhost\\SQLExpress;Initial Catalog=master;Integrated Security=SSPI"