Home > Database > Mysql Tutorial > body text

web.config中配置数据库连接的两种方式

WBOY
Release: 2016-06-07 15:48:10
Original
1382 people have browsed it

在网站开发中,数据库操作是经常要用到的操作, ASP.NET 中一般做法是在 web.config 中配置数据库连接代码,然后在程序中调用数据库连接代码,这样做的好处就是当数据库连接代码需要改变的时候,我们只要修改web.config中的数据库连接代码即可,而不必在修改

在网站开发中,数据库操作是经常要用到的操作,ASP.NET中一般做法是在web.config中配置数据库连接代码,然后在程序中调用数据库连接代码,这样做的好处就是当数据库连接代码需要改变的时候,我们只要修改web.config中的数据库连接代码即可,而不必在修改每一个页面中的数据库连接代码。

在ASP.NET中有两种配置数据库连接代码的方式,它们分别是 appSettings 和 connectionStrings 。在使用 appSettings 和 connectionStrings 配置数据库连接代码时,可分别在 下添加如下代码:

1. appSettings
<appsettings>
<add key="mySqlConnection" value="Provider=SQLOLEDB.1;Data Source=10.0.1.76;Initial Catalog=zfmmias_UAT;Persist Security Info=True; User ID=ias;Password=abcd1234;Connect Timeout=5"></add>
</appsettings>
Copy after login


2、connectionStrings
<connectionstrings>
<add name="mySqlConnection" connectionstring="Data Source=10.0.1.76;Initial Catalog=zfmmias_UAT;Persist Security Info=True; User ID=ias;Password=abcd1234;Connect Timeout=5" providername="System.Data.SqlClient"></add>
</connectionstrings>
Copy after login

appSettings 和 connectionStrings 的区别:

(1) appSettings 是在 2003 中常用的,connectionStrings 是在 2005 中常用的;

(2) 使用 connectionStrings 的好处:

第一,可将连接字符串加密,使用MS的一个加密工具即可;

第二,可直接绑定数据源控件,而不必写代码读出来再赋值给控件;

第三,可方便的更换数据库平台,如换为 Oracle 数据库,只需要修改 providerName。

调用示例:

第1种
string strSqlConString = System.Configuration.ConfigurationManager.AppSettings["mySqlConnection"];
Copy after login
第2种
string strSqlConString = System.Configuration.ConfigurationManager.ConnectionStrings["mySqlConnection"].ToString();
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!