当前位置:编程学习 > C#/ASP.NET >>

数据库连接(急)

如何动态地修改Web.config里的数据库连接字符串,以连接到不同的数据库?(根据需要,数据库服务器SQL Server 2000中开发了若干数据库,当用户身份不同时希望连接到不同的数据库) --------------------编程问答-------------------- 听说 2.0 有直接修改 web.config 的类,可我怎么也找不到是哪个,所以平时只是好用自己写的方法修改.
等知道的人告诉你 2.0 是怎么修改的. --------------------编程问答-------------------- 可以在web.config文件中多配置几个连接串,起几个不同的名字就行了 --------------------编程问答--------------------  楼上的说是可以..不过要全动态的修改,我还不会..顶 --------------------编程问答-------------------- 有高手知道有什么办法修改吗?急啊 --------------------编程问答-------------------- 不会,帮楼主顶顶! --------------------编程问答-------------------- 请下载Dll组件:

http://download.csdn.net/source/303633

然后参考我曾写过的code:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Insus.NET;

public partial class DataBase_CreateDb : BasePage
{
    InitializeDB objInitializeDB = new InitializeDB();
    InsusConfig objInsusConfig = new InsusConfig();
    string strlocalhostName = "localhost";

    protected void Page_Load(object sender, EventArgs e)
    {
        BackHeadContent(elemhead);

        BackLoginAuthorizationed();

        AllowAccessThisPage();

        SystemTitleText1.SetTitleText = "数据库创建";

        if (!IsPostBack)
        {
            Data_Binding();
        }

        objButtonConfirmTip.ConfirmTip(this.btnSaveWF, "数据库连接字符串将写入Web.Config文件中!\\n\\r系统并重启生效!");
    }

    protected void btnCreateDataBase_Click(object sender, EventArgs e)
    {
        Hashtable ht = new Hashtable();
        ht.Add("DataBaseName", this.txtDatabaseName.Text);
        ht.Add("ServerName", this.txtServerName.Text);
        ht.Add("Trused", this.chkTrusted.Checked ? "1" : "0");
        ht.Add("Account", this.txtAccount.Text);
        ht.Add("Password", this.txtPassword.Text);
        try
        {
            objInitializeDB.CreateDataBase(ht);
            objInitializeDB.SaveToWebConfig(ht);
            objInsusUtility.JSAlert("\"" + this.txtDatabaseName.Text + "\" 数据库已经创建成功!");
        }
        catch (Exception ex)
        {
            objInsusUtility.JSAlert(ex.Message);
        }
    }

    protected void chkLocalHost_CheckedChanged(object sender, EventArgs e)
    {
        if (chkLocalHost.Checked)
        {
            this.txtServerName.Text = strlocalhostName;
            this.txtServerName.Enabled = false;
        }
        else
        {
            this.txtServerName.Text = string.Empty;
            this.txtServerName.Enabled = true;
        }
    }

    protected void chkTrusted_CheckedChanged(object sender, EventArgs e)
    {
        this.pnlKey.Visible = chkTrusted.Checked ? false : true;
    }

    protected void btnSaveWF_Click(object sender, EventArgs e)
    {
        ht.Add("DataBaseName", this.txtDatabaseName.Text.Trim ());
        ht.Add("ServerName", this.txtServerName.Text.Trim());
        ht.Add("Trused", this.chkTrusted.Checked ? "1" : "0");
        ht.Add("Account", this.txtAccount.Text.Trim ());
        ht.Add("Password", this.txtPassword.Text.Trim ());
        ht.Add("PacketSize", "8192");
        ht.Add("MaxPoolSize", "100");
        SaveToConfig(ht);
    }

    protected void btnModify_Click(object sender, EventArgs e)
    {
        ht.Add("DataBaseName",this.txtDataBase .Text.Trim ());
        ht.Add("ServerName", this.txtServer.Text.Trim ());
        ht.Add("Trused", this.chkSecurity.Checked ? "1" : "0");
        ht.Add("Account", this.txtUserId.Text.Trim ());
        ht.Add("Password", this.txtPwd.Text.Trim ());
        ht.Add("PacketSize",this.txtPackerSize.Text.Trim ());
        ht.Add("MaxPoolSize", this.txtMaxPoolSize.Text.Trim ());
        SaveToConfig(ht);
    }

    private void SaveToConfig(Hashtable ht)
    {
        try
        {
            objInitializeDB.SaveToWebConfig(ht);
            objInsusUtility.JSAlert("数据库连接字符串已经写入Web.Config中", objInsusUtility.CurrentPageName);
        }
        catch (Exception ex)
        {
            objInsusUtility.JSAlert(ex.Message);
        }
    }

    private void Data_Binding()
    {
        if (objInsusConfig.IsExistKey("appSettings", "InsusConnectionString"))
        {
            this.btnCreateDataBase.Enabled = false;
            this.btnSaveWF.Enabled = false;
        }

        this.txtServer.Text = objInsusConfig.GetServerName();
        this.txtDataBase.Text = objInsusConfig.GetDataBaseName();
        this.txtPackerSize.Text = objInsusConfig.GetPacketSize();
        this.txtMaxPoolSize.Text = objInsusConfig.GetMaxPoolSize();
        this.chkLM.Checked = objInsusConfig.IsAtLocalMachine();
        if (objInsusConfig.IsAtLocalMachine())
        {
            this.txtServer.Enabled = false;
        }
        else
        {
            this.txtServer.Text = string.Empty;
        }


        if (objInsusConfig.IsTrustedSecurityConnection())
        {
            this.txtUserId.Visible = false;
            this.txtPwd.Visible = false;
            this.chkSecurity.Checked = true;
        }
        else
        {
            this.txtUserId.Text = objInsusConfig.GetUserId();
            this.txtPwd.Text = objInsusConfig.GetPassword();
            this.chkSecurity.Checked = false;
        }
    }

    protected void chkLM_CheckedChanged(object sender, EventArgs e)
    {
        if (chkLM.Checked)
        {
            this.txtServer.Text = strlocalhostName;
            this.txtServer.Enabled = false;
        }
        else
        {
            this.txtServer.Text = string.Empty;
            this.txtServer.Enabled = true;
        }
    }

    protected void chkSecurity_CheckedChanged(object sender, EventArgs e)
    {
        if (chkSecurity.Checked)
        {
            this.txtUserId.Text = string.Empty;
            this.txtUserId.Visible = false;
            this.txtPwd.Text = string.Empty;
            this.txtPwd.Visible = false;
        }
        else
        {
            this.txtUserId.Text = objInsusConfig.GetUserId();
            this.txtUserId.Visible = true;
            this.txtPwd.Text = objInsusConfig.GetPassword();
            this.txtPwd.Visible = true;
        }
    }
}
--------------------编程问答-------------------- 貌似有代码可以修改WEB.CONFIG

以下是利用XML来对Web.config文件进行修改:

Modify("Count",this.txtCount.Text.Trim());

/// <summary>
/// 修改web.config文件appsettings配置节中的add里的value属性
/// </summary>
/// <remarks>
/// 注意,调用该函数后,会使整个web application重启,导致当前所有的会话丢失 /// </remarks>
/// <param name="key">要修改的键key</param>
/// <param name="strvalue">修改后的value</param>
/// <exception cref="">找不到相关的键</exception>
/// <exception cref="">权限不够,无法保存到web.config文件中</exception>

private void Modify(string key,string strvalue)
{
string xpath = "/configuration/appSettings/add[@key='Count']";
XmlDocument domwebconfig = new XmlDocument();

domwebconfig.Load(HttpContext.Current.Server.MapPath("/web.config"));
XmlNode addkey = domwebconfig.SelectSingleNode((xpath.Replace("Count", key)));
if (addkey == null)
{
throw new ArgumentException("没有找到<add key=" + key + " value=.../>的配置节");
}
addkey.Attributes["value"].InnerText = strvalue;
domwebconfig.Save(HttpContext.Current.Server.MapPath("/web.config"));

} --------------------编程问答-------------------- 可以参照PETSHOP嘛 --------------------编程问答-------------------- <connectionStrings>
  <add name="stuConnectionString" connectionString="Data Source=.;Initial Catalog=stu;User ID=sa"  providerName="System.Data.SqlClient" />
  </connectionStrings>
这个是再web.config中连接的sql数据库字符,然后再在用她的地方应用它就可以了。
建议:这个链接字符串放到一个类中比较好,用的时候也比较方便。
补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,