W
W
wally2021-09-30 10:33:55
Python
wally, 2021-09-30 10:33:55

Is it possible to get a SQLite database string as a dictionary?

I'm trying to make a small SQLite application using the DB API.
The manual says something like this:

>>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)

As you can see from the example, strings are returned as tuples. Is it possible to get a string as a dictionary column_name -> column_value? If yes, how to do it? As for MySQL found to do, but for SQLite it was not possible to get information. Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-09-30
@Yum1

1. https://docs.python.org/3/library/sqlite3.html#sql...
2. https://docs.python.org/3/library/sqlite3.html#sql...

con = sqlite3.connect("localhost")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute('SELECT * FROM stocks ORDER BY price')
r = cur.fetchone()
print(r['price'])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question