SqlLocalDB是微軟推出專爲開發者本地開發使用的數據庫,安裝包只有33M,而且vs2012版本以上已經默認安裝
這個工具默認在 C:\Program Files\Microsoft SQL Server\110\Tools\Binn(64爲系統,如果是32位的話應該是在C:\Program Files(x86)下)。SqlLocalDB.exe不能直接運行,需要使用cmd打開。
默認情況下它有個實例名爲v11.0
的實例
實例 就是一個 數據庫服務器 不是數據庫文件 非DB
默認是沒有啓動的 啓動
SqlLocalDB
start
v11.0
要想鏈接他就需要 他的 管道 名 使用命令
SqlLocalDB
info v11.0
把最下面的一行實例管道名稱;
複製粘貼到SQL Server Management Studio的連接對話框的服務器名稱
windows 鏈接 就可以了
vs中鏈接
打開數據庫資源管理器------鏈接到數據庫----------服務器名可以是 (localdb)\v11 也可以是管道名
身份爲 window 數據庫可以選 如果沒有就自己填一個他會 創建數據庫的 這裏纔是數據庫文件
項目連接
使用Data Source=管道名;Initial Catalog=數據庫名;Integrated Security=True
或者Server=(localdb)\v11.0;Integrated Security=true來進行數據庫連接。
在C# 代碼裏面用的話 先引入System.Data.SqlClient;命名空間(若提示找不到,那可能是你沒有裝ADO.NET Framework
//數據庫連接字符串,注意這個寫法(localdb)後面必須是兩個斜槓,因爲這中間有個轉義的過程 |
15 |
//Initial
Catalog=要連接的數據庫名 |
16 |
//Intergrated
Security=true 開啓windows身份驗證 |
17 |
string ConnectString
= "Server=(localdb)\\v11.0;Initial
Catalog=數據庫名;Integrated Security=true" ; |
18 |
SqlConnection
con = null ; |
19 |
SqlCommand
cmd = null ; |
20 |
SqlDataReader
str = null ; |
21 |
try {
|
22 |
con
= new SqlConnection(ConnectString);
//連接到數據庫 |
23 |
cmd
= con.CreateCommand(); |
24 |
cmd.CommandText
= "select
footName from dbo.footinfo" ; //T-SQL語句 |
25 |
con.Open(); //創建連接後需要用Open打開連接,結束後要關閉連接,及時釋放資源 |
26 |
str
= cmd.ExecuteReader(); |
27 |
while (str.Read()){ |
28 |
Console.WriteLine(str[0]); |
29 |
} |
30 |
} |
31 |
catch (Exception
ms) |
32 |
{ |
33 |
Console.WriteLine(ms.Message); |
34 |
} |
35 |
finally |
36 |
{ |
37 |
str.Close(); |
38 |
cmd.Clone(); |
39 |
con.Close(); |
40 |
} |