【问题标题】:Accessing multiple databases from SQL Server 2008 R2 in my windows application [closed]在我的 Windows 应用程序中从 SQL Server 2008 R2 访问多个数据库 [关闭]
【发布时间】:2012-12-27 13:12:54
【问题描述】:

如何在我的 Windows 应用程序中从 SQL Server 2008 R2 访问多个数据库?

我想在我的 windows 应用程序中从单个 sqlserver 访问多个数据库。例如:我想从 DB1 中选择学生详细信息,我想从 DB2 中选择员工详细信息,两者都在我的单一 windows 应用程序中使用,那么我应该怎么做怎么办?

【问题讨论】:

  • 你需要更清楚你的场景。您希望如何以及从何处访问这些数据库?
  • 请澄清你的问题,这没有任何意义。
  • @sampath,您为什么以及在哪里访问多个数据库?

标签: c# sql-server-2008-r2


【解决方案1】:

您最好尝试将实体保存在一个数据库中,但如果由于某种原因您不能或不想这样做,解决方案是在您的应用程序中使用多个连接字符串。

根据您选择的 ADO.Net 选择,可以有不同的方式来实现。

编辑:这就是我使用Linq-to-Sql 的方式

我有两个数据库,每个都有一个表,这是架构:

TeachersDB(第一个数据库):
-Teachers {TeacherID [int], TeacherName[string]}

StudentsDB(第二个数据库):
-学生{StudentID [int], TeacherID[int] StudentName[string]}

StudentsDataContext studentsDB = new StudentsDataContext();
TeachersDataContext teachersDB = new TeachersDataContext();

所以每个学生都有一位老师(为了简单起见)

Student st;
Teacher t;

st = (from stu in studentsDB.Students
     where stu.StudentID == int.Parse(txtStudentID.Text)
     select stu).SingleOrDefault<Student>();

t = (from teach in teachersDB.Teachers
    where teach.TeacherID == st.TeacherID
     select teach).SingleOrDefault<Teacher>();

MessageBox.Show(t.TeacherName);

如您所见,我从两个表(每个都在一个单独的数据库中)获取数据并将它们保存在内存中(类对象 st 和 t),然后与它们一起工作并找到学生老师。

希望对你有帮助。

【讨论】:

  • using(SqlConnection conn1 = new SqlConnection("FirstConnectionString")) { DataTable dataFromA = //SELECT id, name FROM TableA } using(SqlConnection conn2 = new SqlConnection("SecondConnectionString")) { DataTable dataFromB = //SELECT id, name FROM TableB }
  • 是的,这是一种实现方式,但您需要将数据存储在某个地方(如 DataSet)才能使用您的数据。
  • @sampath 如果您现在明白了我的意思,您可以在您使用的任何 ado.net 案例中执行此操作,无论您使用的是 DataAdapter,您都可以填充不同的对象并使用它们。
【解决方案2】:

为此,您可以使用不同的connectionstrings,在其中将initial catalog 设置为不同的数据库。
硬编码在代码中,它们看起来像:

SqlConnection conn1 = new SqlConnection("Data Source=YourServer;Initial Catalog=Db1;User   Id=user;Password=pass;")
SqlConnection conn2 = new SqlConnection("Data Source=YourServer;Initial Catalog=Db2;User Id=user;Password=pass;")

并为每个特定查询使用连接字符串。您也可以将它们添加到您的 app.configweb.config

或者当您的connectionstring 中没有指定Initial CatalogUSE MyDbName SELECT * FROM MyTable 时,在查询顶部添加USE MyDbName 在这种情况下,您将对两个数据库使用相同的连接字符串。

【讨论】:

  • 先生请给我详细的代码 plz
  • 先生,实际上我想使用 configmanager,所以通过详细解释解决我的问题。提前谢谢
  • @sampath 为您添加了连接字符串的示例。根据您在问题中提供的信息,恐怕我无法更具体地回答。
  • 谢谢先生........
【解决方案3】:

创建一个 App.Config 文件并在 appsettings 中添加以下内容:

<appSettings>
    <add key="appDSN" value="data source=SERVER-NAME;initial catalog=StudentDB;integrated security=SSPI;persist security info=False;packet size=4096" />
    <add key="appDSN2" value="data source=SERVER-NAME2;initial catalog=EmpolyeeDB;integrated security=SSPI;persist security info=False;packet size=4096" />
</appSettings>

键是您为设置指定的名称,在这种情况下,值是连接字符串

并在连接以从两个数据库中检索数据时使用以下内容:

//
// In a using statement, acquire the SqlConnection as a resource.
//
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["appDSN1"]))
{
    //
    // Open the SqlConnection.
        //
    con.Open();
    //
    // The following code shows how you can use an SqlCommand based on the SqlConnection.
    //
    using (SqlCommand command = new SqlCommand("SELECT * FROM Students", con))
    using (SqlDataReader reader = command.ExecuteReader())
    {
    while (reader.Read())
    {
          //read through the first database
    }
    }
}

//
// In a using statement, acquire the SqlConnection as a resource.
//
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["appDSN2"]))
{
    //
    // Open the SqlConnection.
        //
    con.Open();
    //
    // The following code shows how you can use an SqlCommand based on the SqlConnection.
    //
    using (SqlCommand command = new SqlCommand("SELECT * FROM employees", con))
    using (SqlDataReader reader = command.ExecuteReader())
    {
    while (reader.Read())
    {
          //read through the second database
    }
    }

这是使用 sqlreader 的简单而古老的方法。今天更多的是使用 mahdi tahsildari 方式(Linq to SQL)。

【讨论】:

  • appDSN1 是什么?我没有得到
  • appDSN1 指的是应用程序设置。你可以这样使用它:
  • using(SqlConnection conn1 = new SqlConnection(ConfigurationSettings.AppSettings["appDSN1"])) { DataTable dataFromA = SELECT id 的结果,名称 FROM TableA } using(SqlConnection conn2 = new SqlConnection(ConfigurationSettings.AppSettings ["appDSN2"])) { DataTable dataFromB = SELECT id 的结果,名称 FROM TableB }
  • 您可以获取 appsetting 键(项目的 app.config 中键的名称),它是您的连接字符串。 SQLConnection 将使用连接字符串。使用一次第一个键和一次第二个键,您可以选择两个数据库。本例中的连接信息存储在应用键的值中。
  • 非常感谢每一位......
【解决方案4】:

您将需要 2 个连接字符串, 根据您对方法的需要将其发送到该方法,并将您的网格/数据连接到任何需要的地方。

using(SqlConnection connection = new SqlConnection(<connstring>))
{
connection.Open();

SqlCommand command = new SqlCommand();
command.Connection = connection;

command.CommandText = <query1>;
using(SqlDataReader reader = command.ExecuteReader())
{

DataGrid1.DataSource = reader;
DataGrid1.DataBind();
}

command.CommandText = <query2>;
using(SqlDataReader reader = command.ExecuteReader())
{

DataGrid2.DataSource = reader;
DataGrid2.DataBind();
}
}

【讨论】:

  • 如果您发布代码、XML 或数据示例,在文本编辑器中突出显示这些行,然后单击编辑器上的“代码示例”按钮 ({ })工具栏以很好地格式化和语法突出显示它!
猜你喜欢
  • 1970-01-01
  • 2011-08-08
  • 2017-01-27
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-01
相关资源
最近更新 更多