Home > Software design >  Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot o
Results called before closing connection are not showing / error: sqlite3.ProgrammingError: Cannot o

Time:12-05

The following code is throwing the error 'sqlite3.ProgrammingError: Cannot operate on a closed database.'

Considering that I close the connection after the queries are done, I don't understand why this is happening.

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()

I was trying to query the users database and posts database (2 queries) and then close the connection but an error is happening that doesn't let me do this.

CodePudding user response:

The issue was that i had not added a .fetchall() clause at the end of the query.

Corrected code:

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()
  • Related