如何将MySQL远程数据库表插入本地数据库表?

时间:2016-11-03 09:16:27

标签: php mysql linux

远程服务器数据库(IP:192.168.1.19)

  

数据库名称:RemoteDB

     

表名:RemoteTable

本地服务器数据库(IP:192.168.1.35)

  

数据库名称:LocalDB

     

表名:LocalTable

MySQL查询

INSERT INTO LocalDB.LocalTable SELECT * FROM RemoteDB.RemoteTable

但是,由于数据库连接不同,此查询未执行。

如何从本地服务器( IP:192.168.1.35 )执行此查询?或者任何linux shell命令?

3 个答案:

答案 0 :(得分:2)

mysqldump -uRemoteusername -pRemotepassword -h192.168.1.19 RemoteDB RemoteTable  --set-gtid-purged=OFF  | mysql -h192.168.1.35 -uLocalname -pLocalpassword   LocalDB

答案 1 :(得分:1)

你的问题是使用php插入来自不同数据库的数据,不是吗?

如果您想要同步它们,可以阅读此How to keep two MySQL databases in sync?

从多个数据库使用php插入数据库很简单

$conn1= mysqli_connect($host1,$user1,$pass1);
mysqli_select_db($db1,$conn1);
$conn2= mysqli_connect($host2,$user2,$pass2);
mysqli_select_db($db2,$conn2);

$query=mysql_query("SELECT id,name from tbl_user", $conn1)
while ($row = mysqli_fetch_row($query))
 {
    mysqli_query("insert into tbl_user (id,name) values ('".$row[0]."', '".$row[1]."',$conn2);
 }

答案 2 :(得分:1)

  

我将 CronJob 的已批准答案转换为我的 PHP脚本,如下所示 -

配置:

$remoteDbUser   = '***';
$remoteDbPass   = '***';
$remoteDbHost   = '192.168.1.19';
$remoteDb       = 'RemoteDB';
#$remoteDbTable = '';
$localDbHost    = '192.168.1.35';
$localDbUser    = '***';
$localDbPass    = '***';
$localDb        = 'LocalDB';

同步功能

/*Passing `$remoteDbTable` name as function argument, Because I have many Remote DB table to synchronize with my Local DB table*/
function RemoteDbSynchronze($remoteDbTable='RemoteTable'){
  global $remoteDbUser,
    $remoteDbPass,
    $remoteDbHost,
    $remoteDb,
    $localDbHost,
    $localDbUser,
    $localDbPass,
    $localDb;
  $sql = sprintf(
    "mysqldump -u%s -p%s -h%s %s %s  --set-gtid-purged=OFF  | mysql -h%s -u%s -p%s %s",
    $remoteDbUser,
    $remoteDbPass,
    $remoteDbHost,
    $remoteDb,
    $remoteDbTable,
    $localDbHost,
    $localDbUser,
    $localDbPass,
    $localDb
  );
  shell_exec($sql);
}

从Cron脚本调用函数:

RemoteDbSynchronze('RemoteTable');
RemoteDbSynchronze('AnotherRemoteTable1');
RemoteDbSynchronze('AnotherRemoteTable2');
..........................................
RemoteDbSynchronze('AnotherRemoteTableN');
  

有关sprintfshell_execCron

的更多详情