将Sqlite查询结果设置为变量

时间:2018-07-19 11:28:29

标签: python python-3.x sqlite

问题:

嗨,现在我正在查询sqlite并将结果分配给这样的变量:

表结构:行ID,名称和其他内容

cursor.execute("SELECT * FROM my_table WHERE my_condition = 'ExampleForSO'")
found_record = cursor.fetchone()

record_id = found_record[0]
record_name = found_record[1]
record_something = found_record[2]
print(record_name)

但是,很可能有一天我必须在表中添加一个新列。让我们以添加该列的示例为例:

表结构:行号,年龄,姓名等

在这种情况下,如果我们运行相同的代码,则namesomething的分配将错误,并且打印出来的名称不会是我的名字,而是年龄,所以我必须手动编辑代码以适合当前索引。但是,我现在正在为复杂的UI处理100多个字段的表,并且这样做很麻烦。


所需的输出:

我想知道是否有更好的方法通过使用dict或类似的方法来获取结果:

  

潜伏者注意:下一个被截断的代码是无效的代码,请勿使用。

cursor.execute_to(my_dict, 
                  '''SELECT rowid as my_dict["id"], 
                     name as my_dict["name"], 
                     something as my_dict["something"] 
                     FROM my_table WHERE my_condition = "ExampleForSO"''')

print(my_dict['name'])

我可能对此方法有误,但这与我想要的很接近。这样,如果我不访问结果作为索引,并且如果添加新列,无论它在哪里,输出都将相同。

实现它的正确方法是什么?还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

您可以使用namedtuple,然后在sqlite中指定connection.row_factory。示例:

import sqlite3
from collections import namedtuple

# specify my row structure using  namedtuple
MyRecord = namedtuple('MyRecord', 'record_id record_name record_something')

con = sqlite3.connect(":memory:")
con.isolation_level = None
con.row_factory = lambda cursor, row: MyRecord(*row)

cur = con.cursor()

cur.execute("CREATE TABLE my_table (record_id integer PRIMARY KEY, record_name text NOT NULL, record_something text NOT NULL)")
cur.execute("INSERT INTO my_table (record_name, record_something) VALUES (?, ?)", ('Andrej', 'This is something'))
cur.execute("INSERT INTO my_table (record_name, record_something) VALUES (?, ?)", ('Andrej', 'This is something too'))
cur.execute("INSERT INTO my_table (record_name, record_something) VALUES (?, ?)", ('Adrika', 'This is new!'))

for row in cur.execute("SELECT * FROM my_table WHERE record_name LIKE 'A%'"):
    print(f'ID={row.record_id} NAME={row.record_name} SOMETHING={row.record_something}')

con.close()

打印:

ID=1 NAME=Andrej SOMETHING=This is something
ID=2 NAME=Andrej SOMETHING=This is something too
ID=3 NAME=Adrika SOMETHING=This is new!