sqlite3游标对象返回意外结果

时间:2018-04-03 17:16:12

标签: python sqlite

我试图在python中使用sqlite3模块在只有一列的表中进行数据库查找。该列包含以下格式的电话号码:

9545551212
??? 5551212

这是我在python中运行的内容:

import sqlite3
cti = '/home/user/test/cti.db'
conn = sqlite3.connect(cti)
c = conn.cursor()
c.execute('select * from ani_table_1 where number = 9545551212')
<sqlite3.Cursor object at 0x7f6b435316c0>

当我在sqlite3中运行完全相同的select语句时,我得到了预期的结果:

sqlite> select * from ani_table_1 where number = 9545551212;
9545551212

我使用的是python 3.6.5和sqlite 3.7.17

我的代码中出了什么问题?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你没有对结果进行迭代。 sqlite3命令行工具与Python代码不同;后者总是打印结果,因为它是一个命令行工具,并确保你不会被大型结果集淹没。

但是,在使用代码访问数据库时,库不能假定您要将所有行打印到最终用户。您可能希望对数据执行不同的操作。

所以你需要循环光标并打印每一行:

c.execute('select * from ani_table_1 where number = 9545551212')
for row in c:
    print(*row, sep='\t')

您可能想要熟悉Python数据库API标准的工作原理;寻找一个好的教程。乍一看,this specific tutorial看起来涵盖了最重要的基础知识。

相关问题