2013-05-02 12 views
11

通常、C#を使用してデータベースに接続する必要がある場合は、以下のコマンドルーチンを使用します。
- mysql接続を定義します。
- mysql接続を開きます。
- SQL文/クエリを定義します。
- MySqlCommandを使用してクエリを実行します。C#で1つの接続文字列で2つのデータベースに接続するにはどうすればよいですか?

サンプルコード:

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)" 

それとも、この種の問題のための別の方法がある...

+3

これはC#ではなく、データベースサーバーレベルで設定する必要があります。リンクサーバーはそれを行うための一つの方法です。または、2つの接続文字列を使用して両方のサーバーから結果を取得し、プログラムで必要に応じてデータを操作することもできます。私は他のオプションもあると確信していますが、これはすぐに思い浮かぶ2つのものです。 – Tim

+0

2つの接続を使用し、Linqを使用して結合します。 http://stackoverflow.com/questions/4278993/is-it-possible-to-perform-joins-across-different-databases-using-linqを参照してください – Morten

答えて

8
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〜サーバー間でデータを渡すことだと思います。

+2

私はあなたのコードを試してみましたが、それは働いていましたが、接続文字列に示されている同じサーバー上の複数のデータベースを照会する... db1とdb2が異なる場所にある場合はどうなりますか? (例えば、db1のサーバー=

とdb2のサーバー=
chad

+0

私は唯一のオプションは同時に2つの接続を作成し、手動でそれらの間のデータをC# – mjb