config是configuration的缩写,“配置”的意思。计算机中各类软件及系统都有类似的config文件,其中主要是系统或各软件的配置参数,一般是修改系统配置或设置的。
这次的数据库连接部分就放到了config文件中,为的是解耦,即当改变数据库连接的时候只需用记事本打开config文件进行修改即可,避免了重新编译程序。
具体的编写过程如下:
config文件中:
<connectionStrings>
<add name="connStr" connectionString ="server=.;database=newsSystem;uid=sa;pwd=123" />
</connectionStrings>
SQLHelper中:
首先添加应用:右键添加引用——.NET——system.configuration——确定
增加命名空间:using System.Configuration;
public SQLHelper()
{
string connStr = ConfigurationManager .ConnectionStrings ["connStr"].ConnectionString ;
SqlConnection conn = new SqlConnection(connStr);
}