将连接字符串从[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();