简体   繁体   English

我如何在同一时间连接到两个数据库并在mysql中查询数据

[英]How can connect to two databases in same time and query data in mysql, I have same host

I have two Database, A & B how I can copy data from A to B using MySQL, i did like there something wrong, there are two same tables called members in A & B, and i want copy username from A.members to B.members. 我有两个数据库,A和B,我如何使用MySQL将数据从A复制到B,我确实想出错,在A&B中有两个相同的表,称为成员,我想将用户名从A.members复制到B 。成员。 there is error ! 有错误! can I do that using Mysql, anyone can help me to solve this problem because I must connect to databases A & B in same time then query data 我可以使用Mysql这样做吗,任何人都可以帮助我解决此问题,因为我必须同时连接到数据库A和B然后查询数据

    mysql_connect("$host", "$user", "$pass"); mysql_select_db("A");
    mysql_connect("$host", "$user2", "$pass2"); mysql_select_db("B"); 
   //host A = host B same host 
    $MySQL="Select username FROM A.members INSERT INTO B.members"; 
    $result= mysql_query($MySQL);

If you are connecting to the same host, you only need to make the connection once. 如果要连接到同一主机,则只需建立一次连接。 And setting the default database using mysql_select_db("A"); 并使用mysql_select_db("A");设置默认数据库mysql_select_db("A"); should not be necessary because you are specifying which database to use in your statement. 不必要,因为您正在指定要在语句中使用的数据库。

The SQL for your insert should be: 您插入的SQL应该是:

INSERT INTO B.members (username) SELECT username FROM A.members

Check out the documentation for INSERT...SELECT . 查看INSERT ... SELECT的文档

create two connection and use it in query eg: 创建两个连接并在查询中使用它,例如:

  $con = mysqli_connect("localhost","root","","db1");
        $con2 = mysqli_connect("localhost","root","","db2");
         $query1 = mysqli_query($con1,"SELECT * FROM tbl1 order by ID desc ");
         while($row = $query1 ->fetch_assoc())
      {

         $query2 = mysqli_query($con2,"insert into  tbl2 (fields) values('".$row['field
']."')");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM