二、 建立連接
1. 連接字符串
語法:key1=value1;key2=value2;…
DataSource |
In SQL Server Express |
In SQL Server |
本地默認實例 |
.\SQLEXPRESS (local) (localhost) )\SQLEXPRESS (local)\SQLEXPRESS |
. (local) (localhost) |
非本地非默認實例 |
<主機名/IP>\<實例名> |
Integrated Security:True/False,是否Windows驗證。
例1:DataSource=DataBase1;User ID=sa;Password=sa
例2:DataSource=ServerName;Integrated Security=True;
參考:
http://msdn.microsoft.com/en-us/library/ms130822.aspx
http://www.connectionstrings.com/
A. 手寫連接字符串
string connectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=true";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
// ...
connection.Close();
connection.Dispose();
B. 使用屬性生成器生成連接字符串
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "(local)";
builder.InitialCatalog = "Northwind";
builder.UserID = "user1";
builder.Password = "P@ssw0rd";
MessageBox.Show(builder.ConnectionString);
3. 嚮導建立連接
A. 設計時的連接,連接字符串未存於配置文件中
B. 運行時的連接,連接字符串可以存於配置文件
生成連接的過程完畢,下面的步驟,結束這個嚮導是爲了始之前的操作生效。
程序中讀取鏈接字符串:
Properties.Settings.Default.dbConnectionString