Python SQLite3/从表中选择行
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()
结果是一个元组列表:
[(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))]
代替:
print result
但是每当结果集中有多达 107 行时,我们无法想象像这样迭代变量 i
,然后列出整数.所以,我想知道是否有任何其他替代解决方案可用,无论哪种解决方案都足够直接.
But whenever that there are as much as 107 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. So, I would like to know that if there are any other alternative solutions available for it whichever are efficient enough quite directly.
您可以像这样使用 row_factory
属性:
You can use the row_factory
attribute like this:
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.
您可以阅读有关 row_factory
的更多信息 这里.
You can read more about row_factory
here.