【问题标题】:How to get table name of the executed query? (python / sqlite)如何获取执行查询的表名? (蟒蛇/ sqlite)
【发布时间】:2014-05-23 10:48:25
【问题描述】:

我正在运行一个简单的查询并将结果转换为 json。我想动态地执行此操作,以便我可以使用一个函数来处理所有查询。

query = "INSERT INTO Tests (name, start, end) VALUES (?, ?, ?)"
params = (name, start, end)  
conn = sqlite3.connect('settings.db')
cur = conn.cursor()
cur.execute(query, params)
conn.commit()
rows = cur.fetchall()

我使用 cursor.description 获取列名,但我还需要表名来实现如下所示的 json 结构:

{ status: 'success', tests: [ name: 'sample', 'start': '8484', 'end': '9054' ], [ name: 'sample2', 'start': '84842', 'end': '90542' ] }

有没有合理的方法来实现这一点?

【问题讨论】:

  • 为什么不将表名放入变量中并将其添加到结果集中?查询需要提前知道表名,为什么还要通过结果集来获取呢?
  • 这是一种解决方案,但并不理想,因为这是另一个要创建并传递给函数的变量,您不能将其用于参数化,因此只能用于创建 json。

标签: python python-2.7 sqlite


【解决方案1】:

这是一种从数据库连接中获取表名的方法。 希望对你有用。

cur.execute('''select * from sqlite_master''')
l = cur.fetchall()
#we will populate a list with the names of your tables
tbl_name_list = []
for sql_type, sql_name, tbl_name, rootpage, sql in l:
    if sql_type == 'table':
        tbl_name_list.append(sql_name)
#your list of table names is constructed
print(tbl_name_list)

更多信息: https://sqlite.org/faq.html#q7

【讨论】:

  • 希望避免任何额外的 sql,但我想这可能是唯一的方法。谢谢。
  • @LionelBrooks 这个解析器可以在不实际连接数据库的情况下使用吗?
猜你喜欢
  • 2014-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 2021-12-18
  • 2021-12-08
  • 2023-01-22
相关资源
最近更新 更多