将表数据从MySQL数据库迁移到另一个MySQL数据库

时间:2015-06-02 23:41:27

标签: mysql database-migration

我在理解其工作原理时遇到了一些麻烦。我知道您可以通过一些工作台的工具轻松地将新数据库迁移到MySQL,但我想在这里做的是从另一个数据库的表中获取某些数据以将其插入到我自己的数据库中。问题是这个其他数据库没有相同的表或相同数量的数据。有些对我来说没用,有些不适合我的桌子。

那么经常如何解决这个问题呢?我基本上需要能够捕获数据的东西,无论它过去如何安排,并将其放入我的数据库。当程序不知道会发生什么时,这听起来很难,所以基本上这就是我的问题。如果有人能指出我正确的方向,我会很感激。

2 个答案:

答案 0 :(得分:1)

你不能这样做吗?也许我错过了什么

-- First create your new table, avoid the columns that you don't care about.    
CREATE TABLE newTable......

-- select from the old table only the columns that you need and insert them in the new table
    INSERT INTO newTable(col1, col2, col3)
SELECT col1, col2, col3
FROM oldTable
WHERE .....

如果要在多列之间合并数据,请使用CONCAT_WS

   INSERT INTO newTable(col1, col2, col3)
SELECT CONCAT_WS(' ', col1, col2) AS col1, col3
FROM oldTable
WHERE .....

答案 1 :(得分:0)

您要做的是导入程序。我不确定是否有自动执行此类操作的应用程序。

基本上,您编写的程序连接到您的第一个数据库,提取数据,连接到第二个数据库并从提取的数据生成插入语句。

这是一个简单的python伪代码,可以激发你的灵感:

import mysql.connector

cnx = mysql.connector.connect(user='username', password='password',
                              host='127.0.0.1',
                              database='yourdatabase')
cnx2 = mysql.connector.connect(user='username2', password='password2',
                              host='127.0.0.1',
                              database='yourdatabase2')
cursor = cnx.cursor()
cursor.execute("SELECT * FROM ...")
for (data) in cursor:
  cursor2 = cnx2.cursor()
  cursor2.execute("INSERT INTO ...")       // Use the data variables
  cursor2.close()
cursor.close()
cnx.close()