我有一个通过MAMP管理的mysql数据库(使用端口3306,服务器在端口80上)。我已经从Oracle下载并安装了mysql-connector-python库,正在尝试访问和操作数据库。奇怪的是,按照http://dev.mysql.com/doc/connector-python/en/connector-python-tutorial-cursorbuffered.html上的教程,我能够运行一个查询将新记录插入到特定表中(只要我在连接器上发出.commit()方法)。
然而,我似乎不能用一个简单的select命令检索任何数据。因此,查询"Select * from Assignments“返回None。
query = ('''SELECT title,description FROM `Assignments` LIMIT 0 , 30''')
cursor = cnx.cursor()
result = cursor.execute(query)
print "result:",result
#All assignment info
for (title, description) in results:
print title, description我一直收到错误,"TypeError:'NoneType‘object is not iterable“。我认为这与执行查询的结果为None的事实有关。B/c我能够提交、更新和插入对数据库的更改,我知道我可以很好地连接。为什么我不能运行一个简单的SELECT命令并得到一些东西呢?
发布于 2015-02-09 21:49:13
您应该使用MySQLCursor.fetchall方法来获取结果。
cursor.execute(query)
rows = cursor.fetchall()或
cursor.execute(query)
head_rows = cursor.fetchmany(size=2)
remaining_rows = cursor.fetchall()发布于 2016-12-21 20:19:40
您不需要调用fetchall,如果您查看文档,您将看到没有对execute调用的返回值进行赋值,因为该方法返回None,您只需执行然后迭代MySQLCursor/cursor对象:
query = ('''SELECT title,description FROM `Assignments` LIMIT 0 , 30''')
cursor = cnx.cursor()
# forget assigning, just execute
cursor.execute(query)
# iterate over the cursor
for (title, description) in cursor:
print title, descriptionhttps://stackoverflow.com/questions/28411159
复制相似问题