首页 > 解决方案 > 如何检查 SQL 服务器中的所有记录,存在于 MySQL 中?

问题描述

问题总结

我有一个 Python 脚本,它从 SQL Server 获取数据并将其插入 MySQL 数据库。

为了保持最新信息,我执行以下操作:

  1. 截断表格
  2. 插入从 SQL Server 获取的数据。

如果没有截断,它只会在 MySQL 数据库中添加一堆重复的数据。

问题

我怎样才能只insert从 SQL 服务器到 MySQL 表的值 - 只有两个数据库之间不存在的记录?换句话说,我如何检查 SQL 服务器记录是否已经存在于 MySQL 中?如果确实存在,则不要insert并转到下一条记录。

我需要摆脱使用truncate.

当前代码:

########## FUNCTIONS TO DELETE ALL MYSQL TABLES ########## 

def truncateMJM():
    #Mjm table
    truncateMJMCursor = productionConnection.cursor()
    truncateMJMCursor.execute("Truncate MJM")
    truncateMJMCursor.close()
    productionConnection.commit()

########## FUNCTIONS TO DELETE ALL MYSQL TABLES END ########## 

########## START UP FUNCTION ########## 
def start():

    print("Deleting MySQL tables")
    truncateMJM()

     #Get data from SQL
    sqlCursor = mjmConnection.cursor()
    sqlCursor.execute("SELECT p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name, sol.requiredQty \
         FROM salesorderline sol JOIN \
         salesorder so \
         ON sol.salesorderid = so.id JOIN \
         product p \
         ON sol.productid = p.id JOIN \
         customer c \
         ON so.customerid = c.id \
         WHERE so.orderdate > DATEADD(dd,-35,CAST(GETDATE() AS date));")

    #Send recieved data from SQL query from above to MySQL database
    print("Sending records to MySQL Database")
    mjmCursorMysql = productionConnection.cursor()
    for x in sqlCursor.fetchall():
        a,b,c,d,e,f,g,h = x
        mjmCursorMysql.execute("INSERT INTO mjm (product_id, product_code, product_description, product_weight, \
                salesorder_number, customer_code, customer_name, requiredQty) VALUES (%s,%s,%s,%s,%s,%s,%s,%s);", (a,b,c,d,e,f,g,h))

标签: pythonmysql

解决方案


我在 MySQL 中添加了新的外键列,还id从 SQL 服务器中获取了数字。这将防止 MySQL 端的重复。

最后,我在 Python 中使用了以下查询:

INSERT ignore INTO

我当前的代码中没有其他调整。期待取出功能truncate


推荐阅读