您的位置:首页 > 其它

ADO.NET 4 快速上手(2)——建立连接

2012-12-12 17:14 405 查看

二、 建立连接

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://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring%28v=VS.71%29.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


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: