如何获取已执行查询的表名?(蟒蛇/SQLite) [英] How to get table name of the executed query? (python / sqlite)
本文介绍了如何获取已执行查询的表名?(蟒蛇/SQLite)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在运行一个简单的查询并将结果转换为 json.我想动态地执行此操作,以便我可以使用一个函数来处理所有查询.
I am running a simple query and converting results to json. I would like to do this dynamically so I can use one function to handle all queries.
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 结构:
I am getting column names by using cursor.description but I also need the table names to achieve json structure like below:
{ status: 'success', tests: [ name: 'sample', 'start': '8484', 'end': '9054' ], [ name: 'sample2', 'start': '84842', 'end': '90542' ] }
是否有合理的方法来实现这一目标?
Is there a reasonable way to achieve this?
推荐答案
这是一种从数据库连接中获取表名的方法.希望对你有用.
Here is a method to get the table names from your database connection. I hope that it is useful for you.
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
这篇关于如何获取已执行查询的表名?(蟒蛇/SQLite)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文