如何在web.config中动态添加连接字符串

时间:2013-11-18 10:49:55

标签: asp.net

我必须创建一个应用程序,当用户点击某个控件时,它将在web.config中添加连接字符串。 实际上它运行良好, 但现在与它一起,我必须运行一个SQL脚本,它将创建新的数据库。 为此我写了以下代码.. 现在它给我错误

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Collections.Generic;


public partial class connectionString : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnadd_Click(object sender, EventArgs e)
    {
        try
        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
           // System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            var section = config.GetSection("connectionStrings") as ConnectionStringsSection;
            section.ConnectionStrings.Add(new ConnectionStringSettings(txtNAme.Text, txtNAme.Text, "System.Data.SqlClient"));
            config.Save();

            string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
            FileInfo file = new FileInfo(@"G:\AAA\SCRIPT.sql");
            string script = file.OpenText().ReadToEnd();
            SqlConnection conn = new SqlConnection(sqlConnectionString);
            Server server = new Server(new ServerConnection(conn));
            server.ConnectionContext.ExecuteNonQuery(script);
            file.OpenText().Close();
        }
        catch (Exception ex)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:0)

在web.config中定义连接字符串

     <ConnectionStrings>
 <add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
     </Connectionstrings>

配置是只读的,因此您无法以明显的方式执行此操作,例如

ConfigurationManager.ConnectionStrings["student"].ConnectionString = "new value";