如何在C#中的多个数据库上执行单个命令? [英] How Do I Execute A Single Command On Multiple Databases In C#?

查看:83
本文介绍了如何在C#中的多个数据库上执行单个命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个数据库名称Server1,Server2,Server3和Server4,每个包含一个表。



I have four databases names Server1, Server2, Server3, and Server4 which contains a single table each.

SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["Server1"].ToString());
   SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Server2"].ToString());
   SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["Server3"].ToString());
   SqlConnection con4 = new SqlConnection(ConfigurationManager.ConnectionStrings["Server4"].ToString());





i想在C#中激活以下命令: -





i want to fire the following command in C# :-

select id, filename, Server from Server1.dbo.UploadedData where userid='1'
union
select id, filename,Server from Server3.dbo.UploadedData where userid='1'
union
select id, filename,Server from Server3.dbo.UploadedData where userid='1'
union
select id, filename,Server from Server4.dbo.UploadedData where userid='1'





执行此命令我必须传递每个数据库的连接对象。



喜欢......



for executing this command i have to pass connection object of each database.

like...

cmd= new SqlCommand("select id, filename, Server from Server1.dbo.UploadedData where userid='1'union select id, filename,Server from Server3.dbo.UploadedData where userid='1' union select id, filename,Server from Server3.dbo.UploadedData where userid='1' union select id, filename,Server from Server4.dbo.UploadedData where userid='1',con1,con2,con3,con4 ");





这是不可能传递4个连接对象.......什么是另一个最好的选择??



this is not possible to pass 4 connection object.......what will be the other best option??

推荐答案

这是不可能的!你试图达到的方式无处可去;(



如果你想这样做,请阅读链接服务器 [ ^ ]。

如何创建链接服务器 [ ^ ]



之后,您将能够通过一个命令从所有数据库中获取数据;)
It's impossible! The way you're trying to reach that is going to nowhere ;(

If you want to do it, please read about linked servers[^].
How to Create a Linked Server[^]

After that, you'll be able to get data from all databases in a single command ;)


据我所知,不可能,因为每个数据库都提供不同的连接字符串。因此,您必须明确需要在命令中指定每个连接对象。

但是您仍然可以查看此处 [ ^ ]



-KR
As per my knowledge it is not possible, because every database provides different connection string. Therefore you must explicitly need to specify each and every connection objects in command.
But still you can look at here[^]

-KR


这篇关于如何在C#中的多个数据库上执行单个命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆