protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create a new ConnectionStringSettings object and populate it
ConnectionStringSettings conn = new ConnectionStringSettings();
conn.ConnectionString =
"Server=localhost;User ID=sa;Password=123456; " +
"Database=Northwind;Persist Security Info=True";
conn.Name = "AppConnectionString2";
conn.ProviderName = "System.Data.SqlClient";
// Add the new connection string to the web.config
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("example");
config.ConnectionStrings.ConnectionStrings.Add(conn);
config.Save();
}
}
{
if (!Page.IsPostBack)
{
// Create a new ConnectionStringSettings object and populate it
ConnectionStringSettings conn = new ConnectionStringSettings();
conn.ConnectionString =
"Server=localhost;User ID=sa;Password=123456; " +
"Database=Northwind;Persist Security Info=True";
conn.Name = "AppConnectionString2";
conn.ProviderName = "System.Data.SqlClient";
// Add the new connection string to the web.config
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("example");
config.ConnectionStrings.ConnectionStrings.Add(conn);
config.Save();
}
}
2.修改连接字符串
protected void Page_Load(object sender, EventArgs e)
{
// Retrieve an existing connection string into a Connection String Builder
System.Data.SqlClient.SqlConnectionStringBuilder builder = new
System.Data.SqlClient.SqlConnectionStringBuilder();
// Change the connection string properties
builder.DataSource = "localhost";
builder.InitialCatalog = "Northwind1";
builder.UserID = "sa";
builder.Password = "password";
builder.PersistSecurityInfo = true;
// Save the connection string back to the web.config
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Chapter11");
config.ConnectionStrings.ConnectionStrings["AppConnectionString1"].ConnectionString =
builder.ConnectionString;
config.Save();
}
{
// Retrieve an existing connection string into a Connection String Builder
System.Data.SqlClient.SqlConnectionStringBuilder builder = new
System.Data.SqlClient.SqlConnectionStringBuilder();
// Change the connection string properties
builder.DataSource = "localhost";
builder.InitialCatalog = "Northwind1";
builder.UserID = "sa";
builder.Password = "password";
builder.PersistSecurityInfo = true;
// Save the connection string back to the web.config
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Chapter11");
config.ConnectionStrings.ConnectionStrings["AppConnectionString1"].ConnectionString =
builder.ConnectionString;
config.Save();
}