本文介绍了在同一个应用程序C#中显示来自不同数据库的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,我有我的应用程序MKS,创建了一个数据库MKS_2017并使用它。它工作正常。现在我创建了MKS_2018并使用它也工作正常。



我需要在使用(用户名,密码)登录我的应用程序MKS并在combox中选择数据库在我的应用程序中显示数据(MKS_2017或MKS_2018)



我尝试过:



我以这种方式从服务器读取数据库



I need some help, I have my app MKS, created a database MKS_2017 and using it. It works fine. Now I created MKS_2018 and using it an it also working fine.

I need to implement when login in my app MKS using (username,password) and in combox to choose database to show data in my app (MKS_2017 or MKS_2018)

What I have tried:

I read database from server in this way

public List<string> GetDatabaseList()
{
   List<string> list = new List<string>();

   using (SqlConnection con = new SqlConnection(cs))
   {
       con.Open();
       // Set up a command with the given query and associate
       // this with the current connection.
       using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases where name like 'MKS%'", con))
       {
             using (IDataReader dr = cmd.ExecuteReader())
             {
                        while (dr.Read())
                        {
                            list.Add(dr[0].ToString());
                        }
                    }
              }
            }
            return list;

        }

推荐答案

public static strConnect = "";

您可以在需要时访问它:

and you can access that when you need it:

using (SqlConnection con = new SqlConnection(MyClassWhereIPutIt.strConnect))
   {
   ...
   }

然后你需要做的就是构造连接字符串。有两种方法可以做到这一点:

1)如果您的数据库都使用相同的用户和密码详细信息,那很简单:构建一个基本连接字符串,其中包含数据库名称的占位符:

Then all you need to do is construct the connection string. There are two ways to do this:
1) If you databases all use the same user and password details, it's simple: construct a "basic" connection string with a placeholder for the DB name:

const string basic = @"Server=[server_name]; Database={0}; password=[password]; user = [user_name]";

并使用Replace来设置名称:

And use Replace to set the name:

strConnect = basic.Replace("{0}, nameOfTable);



2)如果他们不这样做,那么你将需要在某处维护一个有效的连接字符串列表(我建议在SQL中的主数据库的表中,它允许您使用WHERE子句中所需的DB名称从SQL获取工作连接字符串。)


2) If they don't, then you will need to maintain a valid connections string list somewhere (I'd suggest in a table in a "master" DB in SQL which lets you fetch a working connection string from SQL using the required DB name in the WHERE clause.)


select top 5* from QA.dbo.user_userdetail as I1 inner join [MOCRollOver2].dbo.user_userdetail I2 on I1.User_ID=I2.User_ID



获取记录如下所示。


Fetching the records are below displayed.

User_ID	UserName	Password
1  	Superdev  1000:F0
2	Admin	  1000:wLVgI5
3	Import    1000:w5


这篇关于在同一个应用程序C#中显示来自不同数据库的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 06:00
查看更多