How to get table name of the executed query? (pyth

2019-03-06 09:02发布

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()

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?

1条回答
来,给爷笑一个
2楼-- · 2019-03-06 09:33

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)

for more info: https://sqlite.org/faq.html#q7

查看更多
登录 后发表回答