使用 PyODBC 和 SQL-Alchemy 同步数据更新

Synchronize Data Update Using PyODBC and SQL-Alchemy

我有一个脚本被多个用户使用。在此脚本中,数据库 table 通过先删除然后上传来更新。

import pyodbc
import sqlalchemy

engine = sqlalchemy.create_engine('credtials', echo=False)
cnxn = pyodbc.connect('credentials')

with pyodbc.connect('...') as cnxn:
    mycursor = cnxn.cursor()
    mycursor.execute('query_delete')
    mycursor.commit()
    mycursor.close()

# Precaluclated dataframe that contains the data (calculation not shown)
df.to_sql(name='db_table', con=engine, index=False, if_exists='append')

问题是有时会发生两个进程时间不当的情况。在这种情况下,流程的顺序是

删除(进程 1) 删除(过程 2) 上传(过程1) 上传(过程 2)

如果发生这种情况,数据就会重复。是否有防止此问题的解决方案?

您可能需要使用类似于此(未经测试)的代码加强事务隔离:

engine = sqlalchemy.create_engine(connection_uri, isolation_level='SERIALIZABLE')
with engine.begin() as conn:
    conn.execute(sqlalchemy.text('DELETE FROM db_table WHERE …'))
    df.to_sql(name='db_table', con=conn, index=False, if_exists='append')
print('Update complete.')