关闭连接前调用的结果未显示/错误:sqlite3.ProgrammingError:无法对已关闭的数据库进行操作

w7t8yxp5  于 2022-12-04  发布在  SQLite
关注(0)|答案(1)|浏览(114)

下面的代码将引发错误“sqlite3.ProgrammingError:无法在关闭的数据库上操作。'
考虑到我在完成查询后**关闭了连接,我不明白为什么会发生这种情况。

import sqlite3

def database():
    connection = sqlite3.connect('database.db')
    connection.row_factory = sqlite3.Row
    return connection

def _index():
    connection = database()
    posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall()
    users = connection.execute('SELECT U.fullname as "username", C.fullname as "committeename" FROM users U JOIN committees C ON U.committee_id = C.id')
    connection.close()

我试图查询用户数据库和帖子数据库(2个查询),然后关闭连接,但发生了一个错误,不让我这样做。

zysjyyx4

zysjyyx41#

问题是我没有在查询的末尾添加.fetchall()子句。
更正代码:

import sqlite3

def database():
    connection = sqlite3.connect('database.db')
    connection.row_factory = sqlite3.Row
    return connection

def _index():
    connection = database()
    posts = connection.execute('SELECT P.title, P.content, P.created, U.username FROM posts P JOIN users U ON P.author_id = U.id').fetchall()
    users = connection.execute('SELECT U.fullname as "username", C.fullname as "committeename" FROM users U JOIN committees C ON U.committee_id = C.id')
    connection.close()

相关问题