错误:对象可以在同一线程中使用

2024-05-05 17:41:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个与此非常相似的项目:GitHub

我有一门课:

class DBfunctions:
    def __init__(self, dbname = '../example.db'):
        self.debname = dbname
        self.conn = sqlite3.connect(dbname)
    def search_db(self, telegram_id):
        telegram_id = (telegram_id,)
        sql = 'SELECT * FROM user WHERE id = ?;'
        row = self.conn.execute(sql,telegram_id)
        return row
    def newuser_db(self, tele_id, name, nick):
        par = (tele_id, name, nick, 0)
        sql = 'INSERT INTO user VALUES(?,?,?,?);'
        self.conn.execute(sql, par)
        self.conn.commit()

我还有一个主要项目:

from file import DBfunctions

db = DBfunction()

def start(update: Update, context: CallbackContext): #befor edit: somethingtodo
    flag = db.search_db(update.effective_user.id)    # here problems start    
    if flag == None:
        db.newuser_db(update.effective_user.id, update.effective_user.first_name, update.effective_user.username)
        update.message.reply_text(
            'Hi!',
            reply_markup=markup,
        )
    else:
        update.message.reply_text(
            'Hey! Welcome back!',
            reply_markup=markup,
        )


def main():
    db.setup() # this function is to create tables if not exist yet
    dispatcher.add_handler(CommandHandler('start', start))
    # other function but nothing correlated

if __name__ == '__main__':
    main()

然后出现错误:

File "filefolder/file.py", line 29, in search_db
    row = self.conn.execute(sql,telegram_id)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 15004 and this is thread id 11036.

我不知道我能做些什么来修复它。。。我不明白我在github上找到的项目有什么不同(链接)


Tags: nameinselfiddbsqldefupdate