python - 如何在 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 并运行所需的脚本?
解决方案
我相信您描述的错误是数据库的连接问题,例如临时网络问题
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")
推荐阅读
- php - MYSQL order by left join 现有行
- powershell - 添加-PSSnapin Windows 10
- javascript - 当值有换行符时在数组中搜索字符串
- sql-server - SQL Server 中的自定义日期时间
- java - Postman 404 弹簧休息api
- python - 从目标函数 Pyomo 打印项的求解结果
- android - ViewModel without reference to View with Camera 2
- python - 如何仅显示值大于 x 的列
- amazon-web-services - 从参数存储访问 SSM 参数
- r - 从R中的日期字段中提取日期部分