简体   繁体   中英

using SQLite 3 with python

I am trying to implement a database in my python 3 program. I am using SQLite 3. I don't really understand how to use my DBHelper class.

In order to use my DBHelper, I would need to instantiate a DBHelper object and call a function (insert, etc.). However, each time I instantiate an object, a new connection is made to my database.

I am confused because it looks like I am connecting to the database multiple times, when I feel like I should only be connecting once at the start of the program. But if I don't instantiate a DBHelper object, I cannot use the functions that I need.

Having multiple connections like this also sometimes locks my database.

What is the correct way to implement SQLite in my program?

Edit: I need to use the same sql db file across multiple other classes

import sqlite3


class DBHelper:
    def __init__(self, dbname="db.sqlite"):
        self.dbname = dbname
        try:
            self.conn = sqlite3.connect(dbname)
        except sqlite3.Error as e:
            log().critical('local database initialisation error: "%s"', e)

    def setup(self):
        stmt = "CREATE TABLE IF NOT EXISTS users (id integer PRIMARY KEY)"
        self.conn.execute(stmt)
        self.conn.commit()

    def add_item(self, item):
        stmt = "INSERT INTO users (id) VALUES (?)"
        args = (item,)
        try:
            self.conn.execute(stmt, args)
            self.conn.commit()
        except sqlite3.IntegrityError as e:
            log().critical('user id ' + str(item) + ' already exists in database')

    def delete_item(self, item):
        stmt = "DELETE FROM users WHERE id = (?)"
        args = (item,)
        self.conn.execute(stmt, args)
        self.conn.commit()

    def get_items(self):
        stmt = "SELECT id FROM users"
        return [x[0] for x in self.conn.execute(stmt)]

You can use singleton design pattern in your code. You instantiate your connection once, and each time you call __init__ it will return the same connection. For more information go to here .

Remember, if you are accessing the connection using concurrent workflows, you have to either implement safe access to the database connection inside DBHelper . Read SQLite documents for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM