MySQL MERGE表使用python跨越不同的数据库

时间:2016-04-21 05:53:02

标签: python mysql

我有一个数据库db1,其中包含表tbl1,tbl2和tbl3。

我还有一个空数据库db2。

如何创建MERGE表mrg1,它合并来自数据库db1的tbl1,tbl2和tbl3的内容,但是使用python / mysql连接器存储在数据库db2中?

此问题与wroberts question相同,但使用python。

这是我尝试过的:

    import mysql.connector

    db1 = 'testaa'
    cnx1 = mysql.connector.connect(user='nev', password='***',host='127.0.0.1',database=db1)
    cursor1 = cnx1.cursor()

    db2 = 'vic'
    cnx2 = mysql.connector.connect(user='nev', password='***',host='127.0.0.1',database=db2)
    cursor2 = cnx2.cursor()

   cnx = [cnx1,cnx2]
   print ("cnx1",cnx1)
   print ("cnx2",cnx2)

   tables = ["RESA","TESTA"]

   # count rows in each table
   for db in cnx:
       cursor = db.cursor()
       for tab in tables:
           query = ("SELECT count(*) FROM %s") % tab
           cursor.execute(query)
           for (count) in cursor:
               print("{} {} {}".format(db,query,count))
    print ("")


    #  merge the tables from vic into testaa
    for tab in tables:
        query = ('insert into {}.{} (select * from {}.{})'.format(db1,tab,db2,tab))
        cursor1.execute(query)

    # run count again to check results
    for db in cnx:
        cursor = db.cursor()
        for tab in tables:
            query = ("SELECT count(*) FROM %s") % tab
            cursor.execute(query)
            for (count) in cursor:
                print("{} {} {}".format(db,query,count))
     print ("")

结果表明成功,表计数加倍,但是当我从mysql查看时没有发生任何变化。

    ('cnx1', <mysql.connector.connection.MySQLConnection object at 0x100f9dd90>)
    ('cnx2', <mysql.connector.connection.MySQLConnection object at 0x100fad310>)
    <mysql.connector.connection.MySQLConnection object at 0x100f9dd90> SELECT count(*) FROM RESA (3,)
    <mysql.connector.connection.MySQLConnection object at 0x100f9dd90> SELECT count(*) FROM TESTA (19,)

    <mysql.connector.connection.MySQLConnection object at 0x100fad310> SELECT count(*) FROM RESA (3,)
    <mysql.connector.connection.MySQLConnection object at 0x100fad310> SELECT count(*) FROM TESTA (19,)

    <mysql.connector.connection.MySQLConnection object at 0x100f9dd90> SELECT count(*) FROM RESA (6,)
    <mysql.connector.connection.MySQLConnection object at 0x100f9dd90> SELECT count(*) FROM TESTA (38,)

    <mysql.connector.connection.MySQLConnection object at 0x100fad310> SELECT count(*) FROM RESA (3,)
    <mysql.connector.connection.MySQLConnection object at 0x100fad310> SELECT count(*) FROM TESTA (19,)

在上面运行后从mysql查看:

    mysql> use testaa;
    Database changed
    mysql> select count(*) from resa;
    +----------+
    | count(*) |
    +----------+
    |        3 |
    +----------+
    1 row in set (0.00 sec)

1 个答案:

答案 0 :(得分:1)

如果您在程序结束时添加此语句:

cnx1.commit()

您将对数据库提交更改。