cha*_*had 11 c# mysql database
通常,当我需要使用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();
Run Code Online (Sandbox Code Playgroud)
我上面的问题是在我使用MySqlCommand命令的部分,因为它是指示数据库连接的位置,以便它现在将查询哪个数据库
MySqlCommand com = new MySqlCommand(sql, con);
Run Code Online (Sandbox Code Playgroud)
其中sql是sql语句,con是用于查询的连接.
如何在一个sql语句中查询两个数据库?
请考虑以下事项:(我正在使用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)"
Run Code Online (Sandbox Code Playgroud)
或者还有另一种解决这类问题的方法吗?......
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();
....
}
Run Code Online (Sandbox Code Playgroud)
sql语句:
select a.ref_no from db1.tbl a where a.ref_no not in (select b.ref_no from db2.tbl b)
Run Code Online (Sandbox Code Playgroud)
您可以一次查询多个数据库.
更新
我认为唯一的选择是同时创建2个连接,并通过C#在2服务器之间传递数据.
归档时间: |
|
查看次数: |
8829 次 |
最近记录: |