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

例如:

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}

谢谢

最佳答案

row只是 dict ionary 。因此,您可以使用.items()生成键和值的序列:

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

关于python pymysql-遍历mysql表的键和值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42485880/

10-12 20:10