【问题标题】:Change connection string from C# code?从 C# 代码更改连接字符串?
【发布时间】:2011-12-15 06:37:37
【问题描述】:

有没有办法以编程方式更改连接字符串?我的意思是用户可以使用组合框选择他想使用的网站,然后在该特定网站上加载用户?

配置代码如下

<add key ="sampleconnectionstring" value="Server=sampleserver;Database=sampledb;User ID=sampleid;Password=samplepassword;Trusted_Connection=False;Encrypt=True;"/>
<add key ="sampleconnectionstring1" value="Server=sampleserver1;Database=sampledb1;User ID=sampleid1;Password=samplepassword;Trusted_Connection=False;Encrypt=True;"/>
<add key ="sampleconnectionstring2" value="Server=sampleserver2;Database=sampledb2;User ID=sampleid2;Password=;Trusted_Connection=False;Encrypt=True;"/>
<add key ="sampleconnectionstring3" value="Server=sampleserver3;Database=sampledb3;User ID=sampleid3;Password=samplepasswrd;Trusted_Connection=False;Encrypt=True;"/>

是否有一种编程方式(如果这是一个词)根据组合框中的所选项目在此连接字符串之间进行更改?任何帮助,将不胜感激。谢谢。

【问题讨论】:

  • 也许我看错了你的问题。我想你在这里有三个问题:1.如何检索连接字符串? 2.如何绑定到组合框? 3.如何设置选中的连接字符串?请澄清是什么问题...
  • @YuvalPeled 我可以检索连接字符串。我可以将它们绑定到组合框。特别是,我的问题在于您的第 3 个问题。感谢您的帮助。

标签: c# silverlight config


【解决方案1】:

根据您使用的数据库,您可以在加载时加载所需的任何连接字符串。

以实体框架为例

Entities model = new Entities(connectionString);

对于 ADO.NET

  using (SqlConnection connection =
        new SqlConnection(connectionString))
    {

    }

对于 Linq To SQL

用途:

MyDataClassesDataContext db = new MyDataClassesDataContext(dynamicConnString);

对于 LinqDataSource,拦截 ContextCreating 事件,如上手动创建 DataContext:

protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
{
    e.ObjectInstance = new MyDataClassesDataContext (dynamicConnString);
}

(Linq to SQL 示例取自:Linq to Sql - Set connection string dynamically based on environment variable

【讨论】:

  • 您可以从任何地方加载连接字符串,我假设您知道如何将它们加载到组合框中?然后它只是将选定的值放入 connectionString 变量中,如上所示。
  • 我目前正在使用 DBML 和 Linq to SQL。那么有任何代码吗?抱歉,我几乎是新手。
  • 这是一个更棘手的问题。幸运的是,已经有人在 StackOverflow 上回答了这个问题:stackoverflow.com/a/1188971/540339。这对你有用吗?
  • 我一定会试试的。非常感谢。
【解决方案2】:

如果每个键与您的组合框项目之一的值相等,您可以直接通过键选择连接字符串。

【讨论】:

    【解决方案3】:

    您可以使用configurationmanager connectionstring collection 获取列表。 然后您可以将组合框绑定到它。类似:

    <ComboBox ItemsSource={Binding ConnectionStrings} DisplayMemberPath="Name" SelectedItem={Binding Path=SelectedConnectionString, Mode=TwoWay} /> 
    

    【讨论】:

      【解决方案4】:

      请记住,连接字符串只是一个字符串。您可以将其他字符串连接到它:

      string CreateConnectionString(string server, string sampledb,  string userid, string password)
      {
         return string.Format("Server={0};Database={1};User ID={2};Password={3}Trusted_Connection=False;Encrypt=True;",server,sampledb,userid,password);
      
      }
      

      【讨论】:

      • 我在哪里退货?如何将其放入 Web.config 文件中?抱歉,我是新手。
      • 啊好的。我不太擅长 Silverlight 和服务来回答您的问题。我只是给你一个例子,向你展示动态创建连接字符串是可能的。你不必使用我的代码。
      【解决方案5】:

      有办法,只需在 Combobox selectedindex changed 事件上设置连接字符串。请参阅下面的代码。首先将默认连接字符串设置为 appconfig 中的第一个字符串,因为在表单加载时 selectedindexchanged 事件不会触发。随时随地获取连接的 ConnString,因为它是一个可以访问的公共属性。

          public string ConnString { get; set; }
          private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
          {
              if (CBox.SelectedIndex == 0)
              {
                  ConnString = getAppSetting("sampleconnectionstring");
              }
              else if (CBox.SelectedIndex == 1)
              {
                  ConnString = getAppSetting("sampleconnectionstring1");
              }
              else if (CBox.SelectedIndex == 2)
              {
                  ConnString = getAppSetting("sampleconnectionstring2");
              }
              else if (CBox.SelectedIndex == 3)
              {
                  ConnString = getAppSetting("sampleconnectionstring3");
              }
          }
          private string getAppSetting(string strKey)
          {
              string strValue = string.Empty;
              XmlReaderSettings settings = new XmlReaderSettings();
              settings.XmlResolver = new XmlXapResolver();
              XmlReader reader = XmlReader.Create("ServiceReferences.ClientConfig");
              reader.MoveToContent();
              while (reader.Read())
              {
                  if (reader.NodeType == XmlNodeType.Element && reader.Name == "add")
                  {
                      if (reader.HasAttributes)
                      {
                          strValue = reader.GetAttribute("key");
                          if (!string.IsNullOrEmpty(strValue) && strValue == strKey)
                          {
                              strValue = reader.GetAttribute("value");
                              return strValue;
                          }
                      }
                  }
              }
              return strValue;
          }
      
          private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
          {
              ConnString = getAppSetting("sampleconnectionstring");
      
          }
      

      【讨论】:

      • 这会改变我的连接字符串吗?我认为这只是改变了 ConnString 的价值。
      • @Nathan,现在查看代码。随时随地获取连接字符串变量值。
      【解决方案6】:

      如果我没记错的话,你一定是在 web.config 文件中这样做的。

      <appSettings>
           <add key = "sampleconnectionstring" ..../>
           <add key = "sampleconnectionstring1" ..../>
           <add key = "sampleconnectionstring2" ..../>
           <add key = "sampleconnectionstring3" ..../>
      </appSettings>
      

      你想以编程方式更改字符串。

      所以,你可以这样做---- 首先,您可以将键名保留在组合框的值字段中。 然后,在下拉/组合框中选择的索引更改为如下所示...

        protected void ddlUrDropdown_SelectedIndexChanged(object sender, EventArgs e)
        {
              // Checking whether first Item "Select......." (index = 0) is selected or not.
              if (ddlUrDropdown.SelectedIndex != 0)
              {
                  // Getting the Selected "Country_Id".
                  string keyName = ddlUrDropdown.SelectedValue;
                  string connectionString = ConfigurationSettings.AppSettings[keyName];
                  // Where keyName can take values like- "sampleconnectionstring" or "sampleconnectionstring1" or "sampleconnectionstring2" or "sampleconnectionstring3"
                  // After getting the connection string according to selected item of combo box, u can create connection and do whatever u want, like below...
                  using(SqlConnection connection = new SqlConnection(connectionString))
                  {
                        connection.Open();
                        // perform work with connection
                   }         
              }
              // Error Message displayed when first Item "Select......." (index = 0) is selected.
              else
              {
                  lblError.Text = "Select any item .";
              }
          }      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-21
        • 1970-01-01
        • 1970-01-01
        • 2012-02-16
        相关资源
        最近更新 更多