【问题标题】:select data from mysql with mysql-connector-python使用 mysql-connector-python 从 mysql 中选择数据
【发布时间】:2015-02-09 13:43:55
【问题描述】:

我有一个通过 MAMP 管理的 mysql 数据库(使用端口 3306,服务器在端口 80 上)。我已经从 Oracle 下载并安装了 mysql-connector-python 库,并且正在尝试访问和操作数据库。奇怪的是,按照http://dev.mysql.com/doc/connector-python/en/connector-python-tutorial-cursorbuffered.html 上的教程,我能够运行查询以将新记录插入到特定表中(只要我在连接器上发出 .commit() 方法)。

但是,我似乎无法使用简单的选择命令检索任何数据。所以查询“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”。我相信这与执行查询的结果为无有关。 B/c 我能够提交更新并将更改插入数据库,我知道我连接得很好。为什么我不能运行一个简单的 SELECT 命令并得到一些东西?

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    您应该使用MySQLCursor.fetchall 方法来获取结果。

    cursor.execute(query)
    rows = cursor.fetchall()
    

    cursor.execute(query)
    head_rows = cursor.fetchmany(size=2)
    remaining_rows = cursor.fetchall()
    

    【讨论】:

    【解决方案2】:

    您不需要调用 fetchall,如果您查看文档,您会发现执行调用的返回值没有赋值,因为该方法返回 None em>,您只需 执行,然后遍历 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, description
    

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 2023-03-30
      • 2016-12-17
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多