Changing connection string dynamically

我的梦境 提交于 2019-12-04 06:48:30

问题


I have a scenario where i am getting dynamically generated databases. I want to create a connection string for each database. So only initial catalog parameter will be changing. Other parameters i ll get it from web config file. It is already having all entries of connection string. I want to change only initial catalog part dynamically based on database created.

Please suggest is there any way to easily to do this.


回答1:


Use SqlConnectionStringBuilder. Set it up from the config file and change the InitialCatalog for each database.




回答2:


use the SqlConnectionStringBuilder class

SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(ConnectionStringFromConfig)
   { InitialCatalog = "your CatalogName" }; // you can add other parameters.

then use this connectionstring where required

conn.ConnectionString;



回答3:


Try with this line of code, it will change the connection string in web config file as you want. I did this with TextBox,

 bool isNew = false;
    string path = Server.MapPath("~/Web.Config");
    XmlDocument doc = new XmlDocument();
    doc.Load(path);
    XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", "conn"));
    XmlNode node;
    isNew = list.Count == 0;
    if (isNew)
    {
        node = doc.CreateNode(XmlNodeType.Element, "add", null);
        XmlAttribute attribute = doc.CreateAttribute("name");
        attribute.Value = "conn";
        node.Attributes.Append(attribute);

        attribute = doc.CreateAttribute("connectionString");
        attribute.Value = "";
        node.Attributes.Append(attribute);

        attribute = doc.CreateAttribute("providerName");
        attribute.Value = "System.Data.SqlClient";
        node.Attributes.Append(attribute);
    }
    else
    {
        node = list[0];
    }
    string conString = node.Attributes["connectionString"].Value;
    SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
    conStringBuilder.InitialCatalog = T1.Text;
    node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
    if (isNew)
    {
        doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
    }
    doc.Save(path);

This may be a hint for your hurdle.



来源:https://stackoverflow.com/questions/23471486/changing-connection-string-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!