11

通常、C# を使用してデータベースに接続する必要がある場合、以下のコマンド ルーチンを使用します。
- mysql 接続を定義します。
- mysql 接続を開きます。
- SQL ステートメント/クエリを定義します。
- MySqlCommand を使用してクエリを実行します。

サンプルコード:

string con1 = "server=<db1 IP>;User Id=user;password=password;Persist Security Info=True;database=db1";
string con2 = "server=<db2 IP>;User Id=user;password=password;Persist Security Info=True;database=db2";
MySqlConnection cn1 = new MySqlConnection(con1);
MySqlConnection cn2 = new MySqlConnection(con2);
MySqlCommand com

cn1.Open();
string sql = "some query";
com = new MySqlCommand(sql, cn1);
com.executeNonQuery();  
cn1.Close();

上記の私の問題は、MySqlCommandコマンドを使用する部分にあります。これは、データベース接続が示されているため、クエリするデータベースが好きになるためです

MySqlCommand com = new MySqlCommand(sql, con);  

ここで、sql は sql ステートメント、con はクエリに使用される接続です。

1 つの SQL ステートメントで 2 つのデータベースにクエリを実行するにはどうすればよいですか?
次のことを考慮してください: (私は MySQL を使用しています)

- I have two databases, db1 and db2.
- db1 is located in City A
- db1 is located in City B
- Both databases have one table (tbl) and they both have the same structure.
- Table structure for tbl:
    +-------------+--------------+------+-----+---------+-------+
    | Field       | Type         | Null | Key | Default | Extra |
    +-------------+--------------+------+-----+---------+-------+
    | id          | int(9)       | NO   | PRI |         |       |
    | ref_no      | int(9)       | NO   |     |         |       |
    | name        | varchar(10)  | YES  |     | NULL    |       |
    +-------------+--------------+------+-----+---------+-------+
- I want to run a query on db1.tbl against db2.tbl
- Example query: "select ref_no from db1.tbl where ref_no not in (select ref_no from db2.tbl)"  

または、この種の問題の別の方法はありますか? ...

4

2 に答える 2

9
string con = "server=localhost;user=root;pwd=1234;";

using (MySqlConnection cn1 = new MySqlConnection(con))
{
    MySqlCommand cmd = new MySqlCommand();
    cmd.Connection = cn1;
    cn1.Open();

    cmd.CommandText = sql;
    MySqlDataAdapter da = new MySqlDataAdapter();
    ....
}

SQL ステートメント:

select a.ref_no from db1.tbl a where a.ref_no not in (select b.ref_no from db2.tbl b)

一度に複数のデータベースにクエリを実行できます。


アップデート

唯一のオプションは、同時に2つの接続を作成し、C#を介して2つのサーバー間でデータを渡すことだと思います。

于 2013-05-02T12:28:45.583 に答える