2017-02-27 28 views
1

我是新来的蟒蛇pymysql, (我红宝石Mysql2宝石之前使用),我想拿到钥匙,并从MySQL表中的值,并做一些动作:Python的pymysql - 遍历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} 

由于

+0

你是什么意思,表**的键和值**?一个表可以有多个列。 –

+0

我更新了我的问题,我希望能够访问每个结果的密钥名称和值名称 – Berlin

回答

2

A row仅仅是一个dict离子。所以,你可以使用.items()生成的序列键和值:

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

right :),从Ruby切换到Python时有点混乱,您是否知道它是否可以使用' pymysql'而不是'MySQL Connector'? – Berlin

+0

@柏林:不幸的是,我不是很熟悉数据库框架等。 –

+0

好的,无论如何。 – Berlin

1

你正在寻找的代码是这样的:

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

使用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)