Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pymysql - iterate through mysql table key and value

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

like image 725
Berlin Avatar asked Feb 27 '17 12:02

Berlin


People also ask

What does PyMySQL Fetchall return?

PyMySQL fetchAll The fetchall function gets all records. It returns a result set. Technically, it is a tuple of tuples. Each of the inner tuples represent a row in the table.

What is the difference between PyMySQL and MySQL?

PyMySQL and MySQLdb provide the same functionality - they are both database connectors. The difference is in the implementation where MySQLdb is a C extension and PyMySQL is pure Python. it might be easier to get running on some systems. it works with PyPy.

How do I display MySQL data in Python?

You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python. The cursor. MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples.


2 Answers

A row is simply a dictionary. 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)
like image 86
Willem Van Onsem Avatar answered Sep 29 '22 05:09

Willem Van Onsem


The code you are looking for is this:

for row in result:
    if row["CAP"] > 1:
        cursor.execute("UPDATE <table> SET row[STATUS]='1' WHERE ID='row[ID]'")
    else:
        continue
like image 44
Meghdeep Ray Avatar answered Sep 29 '22 06:09

Meghdeep Ray