将连接字符串移动到web.config后出现SqlException

时间:2017-04-06 14:37:25

标签: asp.net sql-server sql-server-express

将连接字符串从[server name]\SQLExpress移动到Page_Load后,我必须将数据源更改为服务器web.config的名称。否则,我会在SqlException获得con.Open()。该应用程序可以很好地解决为什么我需要在移动连接字符串后更改数据源名称。

    <connectionStrings>
        <add name="CS"
      connectionString="data source=[server name]\SQLEXPRESS;  Initial Catalog = SampleDb; integrated security = true"
      providerName="System.Data.SqlClient"/>
    </connectionStrings>


 (string cs = "data source=.\\SQLExpress; initial catalog = SampleDb; integrated security= true";)-moved to web.config

        string CS = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;

       //pass the connection string to the SqlConnection() constructor
        SqlConnection con = new SqlConnection(CS);

        //tell sqlcommand what query to execute and which connection
        SqlCommand cmd = new SqlCommand("select * from Electronics", con);

        //open connection
        con.Open();

        //execute the command
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();

        //close the connection
        con.Close(); 

0 个答案:

没有答案