python - 如何检查 SQL 服务器中的所有记录,存在于 MySQL 中?
问题描述
问题总结
我有一个 Python 脚本,它从 SQL Server 获取数据并将其插入 MySQL 数据库。
为了保持最新信息,我执行以下操作:
- 截断表格
- 插入从 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))
解决方案
我在 MySQL 中添加了新的外键列,还id
从 SQL 服务器中获取了数字。这将防止 MySQL 端的重复。
最后,我在 Python 中使用了以下查询:
INSERT ignore INTO
我当前的代码中没有其他调整。期待取出功能truncate
。
推荐阅读
- perforce - 从 p4 仓库路径中提取分支名称
- yocto - yocto recipe 给出错误 -dev package contains non-symlink .so
- python - 使用 tfidfvectorizer 从管道中获取特征名称
- java - 使用 Firebase 消息传递通知时出现空指针异常
- javascript - 使用 Node.js、Express 和 MySQL 的更好方法是什么?
- swift - 如何在 SwiftUI 中将点击事件添加到整个视图
- sql - 通过 sql 查询 (pyodbc) 写入数据帧:pyodbc.Error: ('HY004', '[HY004])
- linux - 删除任何重复行并保持原始顺序的脚本
- vue.js - Vue:更新深度不会触发重新渲染
- java - 我不知道如何处理这个 java.lang.ClassCastException