pymysql获取数据迭代

时间:2017-08-04 07:53:15

标签: python pymysql

每条记录的迭代然后按键显示无显示

#!/usr/bin/env python

# Print necessary headers.
print("Content-Type: text/html")
print()

import pymysql.cursors  
# Connect to the database.
import pymysql
conn = pymysql.connect(db='candidate', user='root',passwd='123',host='localhost')
print ("connect successful!!")
c = conn.cursor()
c.execute("SELECT can_id,can_name,state,total_votes FROM voting")
result_set = c.fetchall()
for row in result_set:
    print(row["can_id"])

print(row)工作正常

2 个答案:

答案 0 :(得分:2)

c = conn.cursor(pymysql.cursors.DictCursor)

conn = pymysql.connect(db='candidate', user='root', passwd='123', host='localhost', cursorclass=pymysql.cursors.DictCursor)

答案 1 :(得分:0)

我建议使用PyMySQL documentation作为参考进行一些更改:

#!/usr/bin/env python
# -*- conding: utf-8 -*-
# Print necessary headers.
print("Content-Type: text/html")
import pymysql.cursors  
# Connect to the database.
# That is important: the order of connection parameters
# 1st host, 2nd user, ...
conn = pymysql.connect(
    host='localhost'
    user='root',
    password='123',
    db='candidate',
    cursorclass=pymysql.cursors.DictCursor # <-- declare cursor class
)
print ("connect successful!!")
try:
    with conn.cursor() as c:
        query = "SELECT can_id, can_name, state, total_votes FROM voting;"
        c.execute(query)
    with c as pointer:
        for row in pointer.fetchall():
            print("Name: %s" % row['can_name'])
finally:
    conn.close()