如何从组合框中选择任何值连接到数据库

发布于 2024-11-04 20:49:05 字数 2335 浏览 0 评论 0原文

我有一个组合框,其中填充了各种数据库名称。我想通过从组合框中选择任何数据库名称来连接到某个数据库。我应该继续这个吗?代码如下。

private void Form1_Load(object sender, EventArgs e)   
      {  XmlDocument doc = new XmlDocument();
     doc.Load("C:\\Documents and Settings\\user\\Desktop\\abc.xml");             XmlNodeList List = doc.SelectNodes("config/dataSources/dataSource");    
         foreach (XmlNode dataSources in List)             
{ comboBox1.Items.Add(dataSources.Attributes["name"].Value.ToString());                    comboBox2.Items.Add(dataSources.Attributes["name"].Value.ToString());      
 }   

    } 

我有另一个带有连接字符串信息的代码

public class DBConnect   
  {        
 string dataSource;    
     string userId;      
   string password;        
 string filepath;          
public DBConnect()       
  {         }     
     public string ConnectionString()  
       {    filepath = ReadRegistry("ConfigFile");     
         XmlDocument doc = new XmlDocument();   
          doc.Load(@filepath);        
      XmlNodeList nodes = doc.SelectNodes
("/config/dataSources/dataSource");        
         foreach (XmlNode node in nodes)  
     {      if (userId.select == node.Attributes["dataSource"].Value)  
               {      dataSource = node.Attributes
["dataSource"].Value;                 
    userId = node.Attributes["userId"].Value;   
        password = node.Attributes["password"].Value;   
        password = Abc.Security.Encryption.Decode(password);
                     break;         

        }       
      }          
   string conn = "Provider=OraOLEDB.Oracle.1;Persist Security Info=False;Password=" + password + ";User ID=" + userId + ";Data Source=" + dataSource + ";";                 return conn;         }          protected string ReadRegistry(string filename)         {             Microsoft.Win32.RegistryKey theKey = Microsoft.Win32.Registry.LocalMachine;             theKey = theKey.OpenSubKey(@"SOFTWARE\Abc, Inc\Abc Marketing");              if (theKey != null)             {                 //string filePath = theKey.GetValue("ConfigFile").ToString();                 filepath = theKey.GetValue(filename).ToString();                 theKey.Close();           
  }    
          return filepath;  
       } 

那么现在我应该如何编写一个代码,从组合框中选择任何数据库名称将我连接到该特定数据库。我是 C# 新手,请建议我一个解决方案。我应该在哪里包含代码?

I have a combobox which is populated with various database name. I want to connect to a certain database on select of any database name from the combobox. Gow should I go about with this? The code for that is as follows..

private void Form1_Load(object sender, EventArgs e)   
      {  XmlDocument doc = new XmlDocument();
     doc.Load("C:\\Documents and Settings\\user\\Desktop\\abc.xml");             XmlNodeList List = doc.SelectNodes("config/dataSources/dataSource");    
         foreach (XmlNode dataSources in List)             
{ comboBox1.Items.Add(dataSources.Attributes["name"].Value.ToString());                    comboBox2.Items.Add(dataSources.Attributes["name"].Value.ToString());      
 }   

    } 

I have another code with connection string information

public class DBConnect   
  {        
 string dataSource;    
     string userId;      
   string password;        
 string filepath;          
public DBConnect()       
  {         }     
     public string ConnectionString()  
       {    filepath = ReadRegistry("ConfigFile");     
         XmlDocument doc = new XmlDocument();   
          doc.Load(@filepath);        
      XmlNodeList nodes = doc.SelectNodes
("/config/dataSources/dataSource");        
         foreach (XmlNode node in nodes)  
     {      if (userId.select == node.Attributes["dataSource"].Value)  
               {      dataSource = node.Attributes
["dataSource"].Value;                 
    userId = node.Attributes["userId"].Value;   
        password = node.Attributes["password"].Value;   
        password = Abc.Security.Encryption.Decode(password);
                     break;         

        }       
      }          
   string conn = "Provider=OraOLEDB.Oracle.1;Persist Security Info=False;Password=" + password + ";User ID=" + userId + ";Data Source=" + dataSource + ";";                 return conn;         }          protected string ReadRegistry(string filename)         {             Microsoft.Win32.RegistryKey theKey = Microsoft.Win32.Registry.LocalMachine;             theKey = theKey.OpenSubKey(@"SOFTWARE\Abc, Inc\Abc Marketing");              if (theKey != null)             {                 //string filePath = theKey.GetValue("ConfigFile").ToString();                 filepath = theKey.GetValue(filename).ToString();                 theKey.Close();           
  }    
          return filepath;  
       } 

So now how should I go about writing a code which on select of any database name from combobox connect me to that specific database. I am new to c# please suggest me a solution. Where should I be including the code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-11-11 20:49:05

好吧,您可以连接 ComboBox 的 SelectedIndexChanged 事件< /a> 当它触发时,您可以从组合框的 SelectedItem 属性 并在连接字符串中使用该属性连接到您的数据库。

示例
您说您已经有一个有效的连接字符串。您需要做的就是允许您的用户更改该字符串的数据源部分。您可以使用 OracleConnectionStringBuilder .DataSource 属性来执行此操作。

在 ComboBox 的 SelectedIndexChanged 事件中更新此属性:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
    // A connection string for testing.
    string connectString = "Server=OracleDemo;Integrated Security=True"
    var builder = new OracleConnectionStringBuilder(connectString);
    // Show your connection string before any change.
    Console.WriteLine("ConnString before: {0}", builder.ConnectionString);
    builder.DataSource = comboBox1.SelectedItem.ToString();
    // This will show your conn string has been updated with the user selected database name.
    Console.WriteLine("ConnString  after: {0}", builder.ConnectionString);

    // At this point you're ready to use the updated connection string.
}

您需要使 ComboBox 使用 DropDownStyle.DropDownList 值,以便用户无法键入自己的数据库名称。

Well, you can wire up your ComboBox's SelectedIndexChanged event and when it fires you can retreive the selected database from the ComboBox's SelectedItem property and use that in your connection string to connect to your database.

Example
You said you already have a working connection string. All you should need to do is allow your users to change the DataSource portion of that string. You can use the OracleConnectionStringBuilder.DataSource property to do this.

Update this property in your ComboBox's SelectedIndexChanged event:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
    // A connection string for testing.
    string connectString = "Server=OracleDemo;Integrated Security=True"
    var builder = new OracleConnectionStringBuilder(connectString);
    // Show your connection string before any change.
    Console.WriteLine("ConnString before: {0}", builder.ConnectionString);
    builder.DataSource = comboBox1.SelectedItem.ToString();
    // This will show your conn string has been updated with the user selected database name.
    Console.WriteLine("ConnString  after: {0}", builder.ConnectionString);

    // At this point you're ready to use the updated connection string.
}

You'll want to make your ComboBox use the DropDownStyle.DropDownList value so users can't type in their own database names.

夏尔 2024-11-11 20:49:05

你可以

SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder("server=(local);user id=ab; password= a!Pass113;initial catalog=AdventureWorks");
builder.InitialCatalog = (string)comboBox1.SelectedItem;

为 Oracle 做

 OracleConnectionStringBuilder builder =
                new OracleConnectionStringBuilder("");//put connection string here
    builder.UserID = (string)comboBox1.SelectedItem;
    OracleConnection conn = new OracleConnection(builder.ConnectionString);
    OracleCommand cmd = new OracleCommand("Select 1 from dual", conn);
    conn.Open();
    int temp = Convert.ToInt32(cmd.ExecuteScalar());
    conn.Close();

希望这有帮助

You could do

SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder("server=(local);user id=ab; password= a!Pass113;initial catalog=AdventureWorks");
builder.InitialCatalog = (string)comboBox1.SelectedItem;

For Oracle do

 OracleConnectionStringBuilder builder =
                new OracleConnectionStringBuilder("");//put connection string here
    builder.UserID = (string)comboBox1.SelectedItem;
    OracleConnection conn = new OracleConnection(builder.ConnectionString);
    OracleCommand cmd = new OracleCommand("Select 1 from dual", conn);
    conn.Open();
    int temp = Convert.ToInt32(cmd.ExecuteScalar());
    conn.Close();

Hope this help

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文