7

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

2
  • What do you mean with the key and value of a table? A table can have multiple columns. Commented Feb 27, 2017 at 12:31
  • I update my question, I want to be able to access the key name and the value name for each result Commented Feb 27, 2017 at 12:35

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

right :), it is a bit confusing when switching from Ruby to Python, do you maybe know if its ok to use 'pymysql' instead of MySQL Connector ?
@Berlin: unfortunately I'm not very familiar with database frameworks, etc.
Could you provide a complete example. With cursor. fetchall() this does not work.
2

Using pymysql, you need to declare the cursor as a dictionary type like below:

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)

1 Comment

Thank you! You can also declare it like this with connection.cursor(DictCursor) as cursor:
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.