我正在为程序编写一个模块,该模块需要侦听数据库中的新条目,并在将新行发布到此表时执行功能……又名触发器。
我已经写了一些代码,但是不起作用。这是我的逻辑:连接到数据库,查询最新行,将该行与变量进行比较(如果不相等),运行函数,将最新行存储到变量,否则关闭。每2秒运行一次,以将最新行与变量/对象中存储的内容进行比较。
一切正常,并从db中获取了预期的结果,但是我在分配之前得到了引用的'局部变量'last_sent'。这使我感到困惑,原因有两个。
我以为在调用函数之前,我将last_sent设置为'nothing'作为全局变量/对象。
为了使我的比较逻辑起作用,我无法在if / else之前在sendListener()函数中设置last_sent
这是代码。
from Logger import Logger
from sendSMS import sendSMS
from Needles import dbUser, dbHost, dbPassword, pull_stmt
import pyodbc
import time
#set last_sent to something
last_sent = ''
def sendListener():
#connect to db
cnxn = pyodbc.connect('UID='+dbUser+';PWD='+dbPassword+';DSN='+dbHost)
cursor = cnxn.cursor()
#run query to pull newest row
cursor.execute(pull_stmt)
results = cursor.fetchone()
#if query results different from results stored in last_sent, run function.
#then set last_sent object to the query results for next comparison.
if results != last_sent:
sendSMS()
last_sent = results
else:
cnxn.close()
# a loop to run the check every 2 seconds- as to lessen cpu usage
def sleepLoop():
while 0 == 0:
sendListener()
time.sleep(2.0)
sleepLoop()
我确信有更好的方法来实现这一目标。
这里:
if results != last_sent:
sendSMS()
last_sent = results
else:
cnxn.close()
Python看到您正在分配给last_sent
,但在此函数中未将其标记为全局,因此它必须是局部的。但是,您正在results != last_sent
其定义前中读取它,因此会出现错误。
要解决此问题,请在函数开头将其标记为全局:
def sendListener():
global last_sent
...