web.config配置文件链接数据库的方法

web.config配置文件链接数据库的方法

  【1】在 web.config配置文件中,
<connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
  【2】在后台中,引入程序集或者手工引入:using System.Web.Configuration;
  【3】后台写入的方法为:
protected void Page_Load(object sender, EventArgs e)
{
//从web.config中引用连接字符串
string strConn = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection myConn = new SqlConnection(strConn);
string strSQL = "SELECT Top 5 CategoryID,CategoryName,Description From Categories";
SqlCommand myCommand = new SqlCommand(strSQL, myConn);
myConn.Open();
myGv.DataSource = myCommand.ExecuteReader();
myGv.DataBind();
myConn.Close();
}

你可能感兴趣的:(web.config配置文件链接数据库的方法)