简体   繁体   English

Python SQLite3 /从表中选择行

[英]Python SQLite3 / Selecting rows from table

board  balls  win1   win2   result
-----  -----  ----   ----   ------
    1      1     0      0        1
    4      1     0      0        1
 1024      1     0      0        1

When we are selecting only one row but multiple columns from a table, for example, by using: 当我们只从表中选择一行但是多列时,例如,通过使用:

connection = sqlite3.connect("spline.db")
crsr = connection.cursor()
crsr.execute("SELECT board FROM positions WHERE balls = 1")
result = crsr.fetchall()
print result
connection.close()

The result is a list of tuples: 结果是一个元组列表:

[(1,), (4,), (1024,)]

Is there any way to get a list of integers directly? 有没有办法直接获得整数列表? One way to do it is with: 一种方法是:

print [result[i][0] for i in range(len(result))]

instead of with: 而不是:

print result

But whenever that there are as much as 10 7 rows in the result set, we cannot imagine of iterating the variable i like that, and then make a list of integers out of it. 但是,只要结果集中有多达10个7行,我们就无法想象迭代变量i喜欢它,然后从中生成一个整数列表。 So, I would like to know that if there are any other alternative solutions available for it whichever are efficient enough quite directly. 所以,我想知道,如果有任何其他替代解决方案可用于它,无论哪种效率都非常直接。

You can use the row_factory attribute like this: 你可以像这样使用row_factory属性:

connection = sqlite3.connect("spline.db")
conn.row_factory = lambda cursor, row: row[0]
crsr = connection.cursor()
crsr.execute("SELECT board FROM positions WHERE balls = 1")
result = crsr.fetchall()
print result
connection.close()

This should give you a list, instead of tuples. 这应该给你一个列表,而不是元组。

You can read more about row_factory here . 您可以在此处阅读有关row_factory更多信息。

You do not need to call fetchall() ; 你不需要调用fetchall() ; you can iterate directly over the cursor: 你可以直接在光标上迭代:

crsr.execute("SELECT ...")
for row in crsr:
    print row[0]

This will compute the result rows on demand, so the entire list never needs to be kept in memory. 这将按需计算结果行,因此整个列表永远不需要保存在内存中。

And you can simplify this further: execute() returns the cursor object itself, and you can use tuple assignment to extract the value(s) from the row: 并且您可以进一步简化: execute()返回游标对象本身,您可以使用元组赋值从行中提取值:

for (board,) in crsr.execute("SELECT board FROM ..."):
    print board

There's almost never a good reason to iterate over range(len(something)) . 迭代range(len(something))几乎没有理由range(len(something)) Always iterate over the thing itself. 总是迭代事物本身。

[row[0] for row in result]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM