Python pymysql - 遍历 mysql table 键和值

Python pymysql - iterate through mysql table key and value

我是 python pymysql 的新手(我之前用 Ruby 和 Mysql2 gem), 我想从 mysql table 获取键和值并执行一些操作:

例如:

dbconnection = pymysql.connect(host=mysql_hostname, user=mysql_username, password=mysql_pass, db=mysql_schema, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
cursor = dbconnection.cursor()
_SQL = (""" 
        select * ...
        """)

cursor.execute(_SQL)
result = cursor.fetchall()
for row in result:
    print(row)
    print("\n")
    # How can I access each key and each value for example: STATUS is the value and 3 is the key
    # I want to do something like this: 
    #'if the value of 'CAP' > 1: change the value of status where the ID key
    #   cursor.execute("UPDATE <table> SET row[STATUS]='1' WHERE ID='row[ID]'")

输出:

{'STATUS': 3, 'ID': 10, 'CAP': 1}
{'STATUS': 3, 'ID': 11, 'CAP': 2}
{'STATUS': 3, 'ID': 12, 'CAP': 3}

谢谢

A row 只是一个 dictionary。所以你可以使用 .items() 来生成一个键和值的序列:

for row in result:
    <b>for key,value in row.items():</b>
        print('The key is %s'%key)
        print('The value is %s'%value)

您要找的代码是这样的:

for row in result:
    if row["CAP"] > 1:
        cursor.execute("UPDATE <table> SET row[STATUS]='1' WHERE ID='row[ID]'")
    else:
        continue

使用pymysql,需要将游标声明为字典类型,如下所示:

import pymysql

connection = pymysql.connect(host="localhost", user="root", passwd="", database="myraces")
#  cursor = connection.cursor()
cursor = pymysql.cursors.DictCursor(connection)

query = "SELECT * FROM `races`"
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
    for key, value in row.items():
        print(key, value)