【问题标题】:Create a class for reading in files: creating an SQL api with distinct methods创建用于读取文件的类:创建具有不同方法的 SQL api
【发布时间】:2017-12-08 07:51:48
【问题描述】:

这个问题更多的是关于如何使用 OOP 读取数据库。 SQLite 和 sqlite3 只是可以使用的示例,并不是问题的主旨:

我正在创建一个软件包,它允许用户查询已经生成的 SQLite 索引文件。对于非常特殊的情况,查询以某种方式索引的 SQLite 文件基本上是一种语法,这应该很简单,但我有点困惑如何“自动”读取 SQLite

这是一个示例(带有伪代码):

import sqlite3

Class EasySQL:
    def __init__(self, filepath):
        self.filepath = filepath

    def connect(self, filepath):  ## perhaps this should be above in init?
        return sqlite3.connect(self.filepath)

    def query_indexA(self):
        ## query index A on SQLite3 connection

我希望在实例化类时“自动”连接到 SQLite 数据库:

### instantiate class
my_table1 = EasySQL("path/to/file")

目前,用户需要在实例化后调用函数.connect()

my_table = EasySQL("path/to/file")
the_object_to_do_queries = my_table.connect()

## now users can actually use this
the_object_to_do_queries.query_indexA()

这似乎是一种糟糕的形式,而且不必要地复杂。

如何编写初始化方法立即创建SQLite3连接?

希望这个问题很清楚。如果没有,我很乐意编辑。

【问题讨论】:

    标签: python python-3.x class oop initialization


    【解决方案1】:

    这里的要点是EasySQL 不应该返回连接(这使得它几乎没有用处),而是通过保留对它的引用在内部使用它:

    class EasySQL(object):
        def __init__(self, filepath):
            self._filepath = filepath
            self._db = sqlite3.connect(self.filepath)
    
        def close(self):
            if self._db:
                self._db.close()
                self._db = None
    
        def query_indexA(self):
            # XXX example implementation
            cursor = self._db.cursor()
            cursor.execute("some query here")
            return cursor.fetchall()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 2015-05-01
      相关资源
      最近更新 更多