Nitin Kumar
Nitin Kumar

Reputation: 85

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. enter image description here

Upvotes: 1

Views: 657

Answers (1)

koushikmln
koushikmln

Reputation: 648

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.

Upvotes: 1

Related Questions