How to write connection string in web.config file and read from it?

后端 未结 7 1287
日久生厌
日久生厌 2020-12-16 00:57

I\'m trying to write Connection string to Web.config like this:


  

        
7条回答
  •  伪装坚强ぢ
    2020-12-16 01:07

    After opening the web.config file in application, add sample db connection in connectionStrings section like this:

      
           
      
    

    Declaring connectionStrings in web.config file:

        
    

    There is no need of username and password to access the database server. Now, write the code to get the connection string from web.config file in our codebehind file. Add the following namespace in codebehind file.

    using System.Configuration;
    

    This namespace is used to get configuration section details from web.config file.

    using System;  
    using System.Data.SqlClient;  
    using System.Configuration;  
    public partial class _Default: System.Web.UI.Page {  
        protected void Page_Load(object sender, EventArgs e) {  
            //Get connection string from web.config file  
            string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
            //create new sqlconnection and connection to database by using connection string from web.config file  
            SqlConnection con = new SqlConnection(strcon);  
            con.Open();  
        }  
    }  
    

提交回复
热议问题