python - python-telegram-bot 中的 SQLite 连接

标签 python python-2.7 sqlite telegram python-telegram-bot

这是我的 Telegram Bot 的简化代码

import telegram.bot, telegram, sqlite3
from telegram.ext import Updater,CommandHandler,MessageHandler,Filters

class DatabaseManager(object):
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        self.conn.execute('pragma foreign_keys = on')
        self.conn.commit()
        self.cur = self.conn.cursor()

    def query(self, arg):
        self.cur.execute(arg)
        self.conn.commit()
        return self.cur

    def __del__(self):
        self.conn.close()


def regcheck(uid):
    for row in dbmgr.query("SELECT * FROM users WHERE id="+str(uid)+";"):
        print "regcheck is running" #this is never printed
        if row == "":
            return 1
        else:
            return 0

def start(bot, update):
    if regcheck(update.message.chat_id) == 1:
        bot.send_message(chat_id=update.message.chat_id, text="OK")
    else:
        bot.send_message(chat_id=update.message.chat_id,text="FAIL")

def main():
    global dbmgr
    dbmgr = DatabaseManager("usr.sql")

    for row in dbmgr.query("select * from users WHERE id="+str(uid)+";"):
        print row #this works perfectly fine

    updater = Updater(token=token)
    dispatcher = updater.dispatcher

    start_handler = CommandHandler('start', start)
    dispatcher.add_handler(start_handler)

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

我知道,为 dbmgr 使用全局变量不是最佳选择,但这是我的第一个 python-telegram-bot 项目,我不知道一种(更好的,或者至少是有效的)方法来实现这一点。

为什么 main() 中的 row 被打印,而 regcheck() 中的 dbmgr.query 被打印> 卡住了?

最佳答案

尝试更改 SQLite 连接的初始化:

self.conn = sqlite3.connect(db, check_same_thread=False)

在这里阅读更多信息:

关于python - python-telegram-bot 中的 SQLite 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47490444/

相关文章:

android - 安装/升级应用程序时有没有办法更新数据库?

python - Bokeh :HoverTool() ColumnDataSource 显示 ???当使用@时

python - 如何从索引矩阵中提取列?

python - 如何使用需要用户定义类型表参数的 SQLAlchemy 调用存储过程

python - 我可以在 Google 应用引擎上将 opencv 与 python 一起使用吗?

python - 迭代包含字典中的键的列。从第二个字典返回匹配的键,保持第一个字典中键的顺序

java - SQLite DB创建表时名称列错误

java - 使用现有 boolean 列类型的房间迁移

python - Pandas:过滤每组数据帧,条件至少匹配组中的一项

python - 如何使用 Numpy reshape ?