Python SQLite3/从表中选择行 [英] Python SQLite3 / Selecting rows from table

查看:35
本文介绍了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.

这篇关于Python SQLite3/从表中选择行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆