python - 将 Sqlite 查询结果设置为变量

标签 python python-3.x sqlite

<分区>

问题:

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

表结构:rowid,name,something

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)

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

表结构:rowid,age,name,something

在那种情况下,如果我们运行相同的代码,namesomething 将被错误地分配,并且打印不会给我名字而是年龄,所以我必须手动编辑代码以适应当前索引。但是,我现在正在为一个复杂的 UI 使用包含 100 多个字段的表格,这样做很烦人。


期望的输出:

我想知道是否有更好的方法通过使用字典或类似的东西来捕获结果:

Note for lurkers: The next snipped is made up code that does not works, do not use it.

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'])

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

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

最佳答案

可以使用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!

关于python - 将 Sqlite 查询结果设置为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51421518/

相关文章:

java - 安卓。 SQLite 异常 : no such column _ingredients

javascript - WebSQL : SQLite Query Returns a Transaction Error

Python从给定字符串中过滤数据

python - 如何在没有窗口的情况下使用 tkinter filedialog

python - 如何使用 .translate() 从 Python 3.x 中的字符串中删除标点符号?

python - 如何调整 QColorDialog 的大小

python - 为什么在 Python 3.6.x/2.7.x 中两个具有相同浮点值的不同变量使用相同的 id()?

mysql - sql多列按最新过滤重复项

python - 无法在 Anaconda/Python3 中导入 clang 绑定(bind)

python - 使用正则表达式提取复杂文本 Python