I am new to python pymysql (I used before Ruby with Mysql2 gem), I want to get the key and the value from mysql table and do some actions:
For example:
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]'")
Output:
{'STATUS': 3, 'ID': 10, 'CAP': 1}
{'STATUS': 3, 'ID': 11, 'CAP': 2}
{'STATUS': 3, 'ID': 12, 'CAP': 3}
Thanks
A row
is simply a dict
ionary. So you can use .items()
to generate a sequence of key and value:
for row in result:
for key,value in row.items():
print('The key is %s'%key)
print('The value is %s'%value)