SQLite Forum

Get other vlues from a row in Python
Login

Get other vlues from a row in Python

(1) By anonymous on 2021-03-09 17:30:13 [source]

I have a Python script that i would want to get all the values from the row it founds the id = 123456. For example, i have 5 columns: id, x1,x2,y1,y2. The id is known by the python script, but i want it to know the other values too.

(2) By Bill Wade (wwade) on 2021-03-09 20:58:06 in reply to 1 [link] [source]

>>> import sqlite3
>>> db = sqlite3.connect('bill.db')
>>> cursor = db.execute('select * from mytable where id = 123456)
>>> row = cursor.fetchone()
>>> print(row)
(123456, 1654, 3, 1558357906, 4271.0625)

Tells you the contents of the row, in column order. If you happen to know the column names, and their order, you can do something like

>>> id,x1,x2,y1,y2 = row
>>> print('y2',y2)
y2 4271.062

To get the names, cursor.description is a tuple of tuples. The inner tuples each describe a column, and the first element is the column name.

>>> print(cursor.description)
(('id', None, None, None, None, None, None), ('x1', None, None, None, None, None, None), ('x2', None, None, None, None, None, None), ('y1', None, None, None, None, None, None), ('y2', None, None, None, None, None, None))

(3) By Keith Medcalf (kmedcalf) on 2021-03-09 21:23:49 in reply to 2 [link] [source]

Note that you can also set a row_factory so that the returned row is some construct from the row tuple or the builtin sqlite3.Row object, in which case you can access the returned "row" as if it were a dictionary specifying the column name as the index into the dictionary.

This would then look something like this:

>>> import sqlite3
>>> db = sqlite3.connect('bill.db')
>>> db.row_factory = sqlite3.Row
>>> cursor = db.execute('select * from mytable where id = 123456)
>>> row = cursor.fetchone()
>>> print('y2',row['y2'])
y2 4271.062