简体   繁体   中英

Unable to fetch results from SQL to Python using mysql.connector

I am trying to query a table stored in SQL using python. I am using mysql.connector package to perform the task.

          import mysql.connector


          #Creating a connection
          mydb = mysql.connector.connect(
          host="localhost",
          user="root",
          passwd="something",
          database='mydatabase',
           )
          print(mydb)

          ##Creating a table called customers
          mycursor = mydb.cursor()
          mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")

          #Inserting records to the table
          sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
          val = [
          ('Peter', 'Lowstreet 4'),
          ('Amy', 'Apple st 652'),
          ('Hannah', 'Mountain 21'),
          ('Michael', 'Valley 345')]

          mycursor.executemany(sql, val)
          mydb.commit()
          print(mycursor.rowcount, "record inserted.")

The problem is when I query the database, there is no output displayed.

           query=("SELECT name, address FROM customers")
           mycursor.execute(query)

           for (name, address) in mycursor:
                 print("{}  {}".format(name, address))

Here is a link to what I tried and where I got the code from. Link: https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html

Here is the confirmation that the query is storing rows in the database. 在此处输入图像描述

The code is running fine. The issue seems to be in the line mycursor.executemany(sql, oval) as the variable is defined as val above. Fixing that should give you the expected output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM