【问题标题】:Receiving table information in python/sql to print to console [duplicate]在python / sql中接收表信息以打印到控制台[重复]
【发布时间】:2016-04-27 05:29:41
【问题描述】:
class DatabaseManager(object): ##Ignore the indentation##
def __init__(self, db):
    self.conn = sqlite3.connect(db)
    self.conn.execute('pragma foreign_keys = on')
    self.conn.commit()
    self.c = self.conn.cursor()


def query_params(self, arg, params=None):
    self.c.execute(arg, params)
    self.conn.commit()
    return self.c

def query(self, arg):
    self.c.execute(arg)
    self.conn.commit()
    return self.c

def fetch(self):
    self.c.fetchall()
    self.conn.commit()
    return self.c

def __del__(self):
    self.conn.close()

dbmgr = DatabaseManager("connect.db")

其他代码 …… …… …… 然后:

def read_from_db():

    tables = []
    query = "SELECT name FROM sqlite_master WHERE type='table'"
    dbmgr.query(query)
    rows = dbmgr.fetch()
    for row in rows:
        tables.append(row)
    print (tables)

我无法弄清楚如何查看我的数据库中的表,它们是真实的,因为我可以在我的 sqlite 管理器中看到它们。当我没有上课时,这曾经有效,只是做了:

    def read_from_db():

    tables = []
    c.execute("SELECT name FROM sqlite_master WHERE type='table'")
    rows = c.fetchall()
    for row in rows:
        tables.append(row)
    print (tables)

【问题讨论】:

    标签: python database sqlite


    【解决方案1】:

    所以,你获取结果,但从不对其做任何事情,然后返回用过的游标......

    def fetch(self):
        self.c.fetchall() # this returns a list of your data 
        self.conn.commit()
        return self.c
    

    也不清楚你在函数中提交了什么

    与您的其他代码比较,

    rows = c.fetchall()
    

    所以你应该只需要

    def fetch(self):
        return self.c.fetchall()
    

    那就叫吧

    tables = dbmgr.fetch()
    

    或者,或者,或者

    tables = dbmgr.query(query).fetchall()
    

    请注意,您正在创建一个空列表,然后将列表的元素添加到该列表中。您可以通过直接分配表来缩短该过程

    【讨论】:

      猜你喜欢
      • 2020-02-19
      • 1970-01-01
      • 2017-05-29
      • 2014-02-20
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      相关资源
      最近更新 更多