实现python db侦听器时出现问题

时间:2020-01-17 21:40:30

标签: python while-loop

我正在为一个程序编写模块,该模块需要侦听db中的新条目,并在将新行发布到此表时执行一个函数……又称为触发器。

我已经写了一些代码,但是没有用。这是我的逻辑: 连接到数据库,查询最新行,将该行与变量进行比较(如果不相等),运行函数,将最新行存储到变量,否则关闭。每2秒运行一次,以将最新行与变量/对象中存储的内容进行比较。

一切正常,并从数据库中获取预期结果,但是在赋值之前,我得到了引用的“本地变量” last_sent”。 这使我感到困惑,原因有两个。

  1. 我以为我在调用函数之前将last_sent设置为“ nothing”作为全局变量/对象。

  2. 为了使我的比较逻辑起作用,我无法在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()

我敢肯定有一种更好的方法来实现这一点。

1 个答案:

答案 0 :(得分:1)

这里:

if results != last_sent:
    sendSMS()
    last_sent = results
else:
    cnxn.close()

Python看到您正在分配给last_sent,但是此函数未将其标记为全局,因此它必须是局部的。但是,您在定义之前在results != last_sent 中读取它,因此会出现错误。

要解决此问题,请在函数开头将其标记为全局:

def sendListener():
    global last_sent
    ...