【转发】C#连接sql server数据库的方法

1、连接SQLEXPRESS

A)、连接到 SQLServer Express Edition 数据库,下面的连接字符串连接到一个名为 Database1 的数据库:

DataSource=.\SQLEXPRESS;Initial Catalog=Database1;Integrated Security=True;

B)、连接数据库文件Database1(VS自带SQLEXPRESS)

DataSource=.\SQLEXPRESS;AttachDbFileName=D:\Projects\CrystalReports\WebUI\Database1.mdf;IntegratedSecurity=True;User Instance=True;

如果存在于WEB应用程序的App_Data 目录中,可以用|DataDirectory| 连接字符串变量,以代替应用程序的 App_Data 目录的文件路径,简便且能够提高应用程序的数据安全性,如下:

DataSource=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Database1.mdf;IntegratedSecurity=True;User Instance=True;

注意:当User Instance设置为true时,SQL ServerExpress Edition只允许有单个连接连到.mdf文件。

2、连接SQL SERVER(非SQLEXPRESS)

DataSource=服务器名\实例名;Initial Catalog=库名;Persist Security Info=True;User ID=sa;Password=123456;

Data Source=服务器名\实例名;Initial Catalog=库名;Integrated Security=True;

Data Source=服务器名\实例名;Initial Catalog=库名;Integrated Security=True;

注意:服务器名也可以是IP地址。当Pooling设置为true时,SQL连接将从连接池获得,如果没有则新建并添加到连接池中。pooling=false是关闭连接池,系统默认的是开启的。另外,当选择pooling=FALSE的时候,由于网络中断造成的数据库连接中断,可以重新连接,为TRUE就不可以,但为True时访问速度更快。

3、从配置文件中获取连接字符串

A)、如果连接字符串是配置在web.config或app.config中的,获取方式如下。

web.config或app.config中

<appSettings>
<add key="ConnectionString"value="server=服务器名\实例名;database=库名;uid=sa;pwd=123456;Pooling=true;" />
</appSettings>

获取字串代码:

string connectStr= ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

转自:https://blog.csdn.net/hp_bigpig/article/details/37596485

posted @   James·wang  阅读(313)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2014-05-21 在mvc4里怎样引用:System.Web.Optimization和entityframework
2014-05-21 【转】Asp.Net MVC4 之Url路由
点击右上角即可分享
微信分享提示