首页 > 解决方案 > 如何在 python 中使用 SQLalchemy 在数据库中有新条目时运行脚本?

问题描述

我是 SQL Alchemy 的新手,每当向表中添加新条目时,我都需要一种方法来运行脚本。我目前正在使用以下方法来完成任务,但我确信必须有更有效的方法。

我将 python 2 用于我的项目并使用 MS SQL 作为数据库。

假设我的表是 carData,并且我从网站添加了一个新的汽车详细信息行。新的汽车数据被添加到 carData。我的代码如下

class CarData:
    <fields for table class>

with session_scope() as session:
    car_data = session.query(CarData)
    reference_df = pd.read_sql_query(car_data.statement, car_data.session.bind)

while True:
    with session_scope() as session:
        new_df = pd.read_sql_query(car_data.statement, car_data.session.bind)
        if len(new_df) > len(reference_df):
            print "New Car details added"
            <code to get the id of new row added>
            <run script>
            reference_df = new_df
    sleep(10)

上面当然是我正在使用的代码的一个更简单的版本,但想法是有一个参考点,然后每 10 秒检查一次是否有新条目。但是,即使在使用 session_scope() 之后,几天后我还是看到了连接问题,因为这个脚本应该无限期地运行。

有没有更好的方法来知道已添加新行、获取新行的 id 并运行所需的脚本?

标签: pythonsql-serverdatabasepython-2.7sqlalchemy

解决方案


我相信您描述的错误是数据库的连接问题,例如临时网络问题

OperationalError:TCP 提供程序:错误代码 0x68

因此,您需要做的是通过错误处理来满足这一点!

try:
    new_df = pd.read_sql_query(car_data.statement, car_data.session.bind)
except:
    print("Problem with query, will try again shortly")

推荐阅读