pymysql - python3.5操作数据库中fetchall的问题

查看:896
本文介绍了pymysql - python3.5操作数据库中fetchall的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

import pymysql.cursors
import networkx as nx

Connect to the database

connection = pymysql.connect(host='localhost',

                         port=3306,
                         user='root',
                         password='',
                         db='shortest',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)

执行sql语句

try:

    cursor = connection.cursor()
    # 执行sql语句,进行查询
    sql = 'SELECT author1,author2,year FROM shortest WHERE id < 200'
    cursor.execute(sql)
    # 获取查询结果
    result = cursor.fetchall()
    for row in result:
        author1 = row[1]
        author2 = row[2]
        year = row[3]
        # 打印结果
        print
        "auther1=%s,author2=%s,year=%s" % \
        (myauther1, myauther2, myyear)
    # 没有设置默认自动提交,需要主动提交,以保存所执行的语句
    connection.commit()

finally:

connection.close();

这个代码我感觉没有问题,但是编译器却报错!!!
Traceback (most recent call last):
File "E:/Python Work/beta1/test.py", line 21, in <module>

author1 = row[1]

KeyError: 1

希望高手可以解释指点一下,谢谢啦!

解决方案

应该是result是一个字典结构,在python中需要用dict['Name']这样的形式使用吧。具体可百度字典用法。

这篇关于pymysql - python3.5操作数据库中fetchall的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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