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

Summer ·
更新时间:2024-11-13
· 581 次阅读

  【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 Web 方法 数据 config 数据库

需要 登录 后方可回复, 如果你还没有账号请 注册新账号