Python中的基本SQLite数据库访问问题
我有一个名为“default.db”的数据库,它是一个工作数据库[我可以通过SQLite实用程序访问它并查看其中的表] 我有以下访问数据库的代码:Python中的基本SQLite数据库访问问题,python,sqlite,Python,Sqlite,我有一个名为“default.db”的数据库,它是一个工作数据库[我可以通过SQLite实用程序访问它并查看其中的表] 我有以下访问数据库的代码: from pysqlite2 import dbapi2 as sqlite conn = sqlite.connect("default.db") cur = conn.cursor() #retrieve all database data cur.execute("SELECT name FROM sqlite_master WHERE
from pysqlite2 import dbapi2 as sqlite
conn = sqlite.connect("default.db")
cur = conn.cursor()
#retrieve all database data
cur.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;")
print "fetch all"
cur.fetchall()
print "printing"
print cur
print conn
for i in cur:
print "item"
print i
输出为:
fetch all
printing
<pysqlite2.dbapi2.Cursor object at 0xb74a2de0>
<pysqlite2.dbapi2.Connection object at 0xb74713d8>
done
我的问题是:我如何解决这个问题,出了什么问题?我没有收到任何错误连接到数据库[它没有报告任何]
编辑:我试图将fetchall保存到一个变量中,但该变量打印为[]。(空)您可能应该阅读。但基本上,光标本身是不可编辑的。方法,例如
fetchall
返回列表,如上一个示例所示。第一个示例返回列表,但被丢弃(未分配)
从该文档中,fetchall执行以下操作:
获取查询的所有(剩余)行
结果,将它们作为序列返回
序列(例如元组列表)。
请注意,光标的arraysize
属性可以影响的性能
这次手术
我认为您应该迭代
cur.fetchall()
而不是cur
->光标本身
应该是这样,
for i in cur.fetchall():
print "item"
print i
您还应该删除前面的cur.fetchall()
命令。cur.fetchall()
检索所有行,但不将它们保存在变量中。更改为print cur.fetchall()
并在脚本中删除它后面的所有内容,或者将fetchall
注释掉,迭代器将工作:
例子
输出
问题是,该数据库在预期的位置不存在。反过来,它只是创建了一个空文件和数据库。Iterable游标是可选的,但SQLite支持它们。@cristian这里的证据表明它不支持。;-)第一个
cur.fetchall()
将耗尽迭代器<如果注释fetchall
out.Aha,则代码>for i in cur有效。我在政治公众人物中没有看到这一点。但是我认为光标和fetchall是两种不同的东西,它们会像那样相互影响,这是不明显的,也是一种值得怀疑的设计。cur.fetchall()打印一个列表,但您没有告诉它打印任何内容。这表明cur.fetchall()返回一个值,并且代码没有将该值赋给变量。因此,您将丢弃查询结果。注意文档,函数参数和函数结果。我希望它能在脚本中打印出来,这就是为什么我没有给它赋值。这是脚本后来的附加组件。您的建议不会打印任何内容。您只能在同一个游标上运行一次fetchall,因此必须确保删除前一个cur.fetchall()。第一个cur.fetchall()会耗尽迭代器。删除第一个选项或在此选项之前重新执行select,它将起作用。
for i in cur.fetchall():
print "item"
print i
import sqlite3
db = sqlite3.connect(':memory:')
cur = db.cursor()
cur.execute('create table a(a,b,c,d)')
cur.execute('insert into a values(1,2,3,4)')
cur.execute('insert into a values(2,3,4,5)')
cur.execute('insert into a values(3,4,5,6)')
cur.execute('insert into a values(4,5,6,7)')
cur.execute('select * from a')
for i in cur:
print i
(1, 2, 3, 4)
(2, 3, 4, 5)
(3, 4, 5, 6)
(4, 5, 6, 7)