The following initial situation:
I have a Python script with which I fetch data from SQLite databases via SELECT statements.
For example:
sql_statement = ''' SELECT * FROM results WHERE id=1 '''
Output:
[(1, '2022-05-01 12:00:00', 'test')]
Target:
But I want my output to include the names of the database columns, so the output should look like this, for example:
[(id=1, date='2022-05-01 12:00:00', content='test')]
or
[(id:1, date:'2022-05-01 12:00:00', content:'test')]
or
[([id,1], [date,'2022-05-01 12:00:00'], [content,'test'])]
It is only important to me that it is a combination of table column names and their selected value (no matter whether as tuple, list, JSON, ...).
Question:
How do I adjust my SQL statement so that I get the desired result without having permanently changed row_factory?
Thank you very much for your help!
Addition:
I have already looked at PRAGMA table_info('table_name')
, .headers on
and also .mode column
, but unfortunately they did not help me with my solution.
I would like to do this for a single query and therefore not change the row_factory if possible.
Possible ideas as approaches
A theoretical idea would also create two statments, which are then aggregated, e.g.
SELECT * FROM results WHERE id=1
with
SELECT 'name' FROM PRAGMA table_info('results')
python code
import sqlite3
database = "db.db"
db_conn = sqlite3.connect(database)
db_cursor = db_conn.cursor()
id=1
sql_statement = ''' SELECT * FROM results WHERE id=''' + str(id) + ''' '''
db_cursor.execute(sql_statement)
fetch_result = db_cursor.fetchall()
db_conn.close()
print(fetch_result)
sql code
CREATE TABLE "results" (
"id" INTEGER NOT NULL UNIQUE,
"date" TEXT NOT NULL,
"content" TEXT NOT NULL,
PRIMARY KEY("id" AUTOINCREMENT)
)