简体   繁体   English

在 python 中使用 SQLite 3

[英]using SQLite 3 with python

I am trying to implement a database in my python 3 program.我正在尝试在我的 python 3 程序中实现一个数据库。 I am using SQLite 3. I don't really understand how to use my DBHelper class.我正在使用 SQLite 3。我真的不明白如何使用我的 DBHelper 类。

In order to use my DBHelper, I would need to instantiate a DBHelper object and call a function (insert, etc.).为了使用我的 DBHelper,我需要实例化一个 DBHelper 对象并调用一个函数(插入等)。 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.但是如果我不实例化一个 DBHelper 对象,我就不能使用我需要的函数。

Having multiple connections like this also sometimes locks my database.像这样的多个连接有时也会锁定我的数据库。

What is the correct way to implement SQLite in my program?在我的程序中实现 SQLite 的正确方法是什么?

Edit: I need to use the same sql db file across multiple other classes编辑:我需要在多个其他类中使用相同的 sql db 文件

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.您可以在代码中使用singleton设计模式。 You instantiate your connection once, and each time you call __init__ it will return the same connection.您将连接实例化一次,每次调用__init__它都会返回相同的连接。 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 .请记住,如果您使用并发工作流访问连接,则必须在DBHelper实现对数据库连接的安全访问。 Read SQLite documents for more information.阅读SQLite 文档以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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