Sherlock
Sherlock

Reputation: 5627

Sqlite query returns different results from different classes

I have a repository class that returns data from an sqlite database. Here is a basic example:

class FeedbackRepository:
    def __init__(self):
        self.connection = sqlite3.connect('feedback.db')
        self.cursor = self.connection.cursor()
        self.setupDatabase()

    def setupDatabase(self):
        sql = """
                  CREATE TABLE IF NOT EXISTS FeedbackEntries
                  (
                      id TEXT NOT NULL,
                      rep TEXT,
                      rating TEXT NOT NULL
                  )
              """
        self.cursor.execute(sql)
        self.connection.commit()

    def getAllFeedback(self):
        sql = """SELECT * FROM FeedbackEntries"""
        self.cursor.execute(sql)
        data = self.cursor.fetchall()
        return [self._getFeedbackEntryModelFromRow(row) for row in data]

I am creating an instance of this class in two different .py files, and each time I call getAllFeedback(). In one file, all of the feedback is returned from the database query. The second file, returns an empty collection from the cursor.fetchall(). The code from the two files does not run concurrently, I run the scripts at separate time, and so there should never be more than one connection at any time (if that even makes a difference).

I have no idea how this could happen, especially as both scripts are using the same code ?

Upvotes: 0

Views: 151

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124738

You are using a relative path in the sqlite3.connect() call; this means the exact location of the database file depends on the current working directory. If you execute the script from a different location, the database file will be re-created.

Use an absolute path instead; you can base it of the location of the module with:

import os

_module_directory = os.path.dirname(os.path.abspath(__file__))

then:

self.connection = sqlite3.connect(os.path.join(_module_directory, 'feedback.db'))

Upvotes: 1

Related Questions