在web.config文件:加在</configSections>后面
<connectionStrings>
<add name="SqlConnection" connectionString="Data Source=MING-THINK\SQLEXPRESS;database=ming;uid=sa;pwd=sasasa" providerName="System.Data.SqlClient"/>
</connectionStrings>
注:可能会出现connectionStrings错误是因为Framework版本不正确导致的。修改版本即可
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration; //ConfigurationManager的名称空间
using System.Text; //StringBuilder的名称空间
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string name = "SqlConnection";
string connectionString = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;//中括号中的内容为web.config中的name
string providerName = ConfigurationManager.ConnectionStrings["SqlConnection"].ProviderName;
StringBuilder builder = new StringBuilder(string.Empty);
builder.AppendFormat("<b>连接字符串键名:{0}</b><br/>",name);
builder.AppendFormat("<b>数据库连接字符串:{0}</b><br/>", connectionString);
builder.AppendFormat("<b>数据提供程序名称:{0}</b><br/>", providerName);
this.Response.Write(builder.ToString());
}
}
使用connectionStrings配置节点配置连接字符串后,任何连接字符串头可以通过ConfigurationManager静态类ConnectionStrings静态属性获取。
web.config:
name:连接字符串的键名
providerName:System.Data.SqlClient为sqlserver数据库。Mysql.Data.MysqlClient使用Mysql数据库
connectionString:配置的连接字符串