'displaying data of table from database using python

I am newbie to python ,trying with simple programs given below is a program which i tried to get the data from table and displaying it. Installed Python3.4 and mysql.connector 2.0.4, runningin localhost as http://localhost:804/cgi-bin/ex7.py

It's connecting to database but not fetching the data from table

 #!"C:\python34\python.exe"
    import sys
    import mysql.connector
    print("Content-Type: text/html;charset=utf-8")
    print()
    conn = mysql.connector.connect(host='localhost',port='8051',
                                           database='example',
                                           user='root',
                                           password='tiger')
   cursor = conn.cursor()
 if conn.is_connected():
        print('Connected to MySQL database')
    cursor.execute(""" SELECT * FROM album """)
    for row in cursor:
        print (row[1])

It's giving output as : Connected to MySQL database

not printing data from table Please suggest where went wrong



Solution 1:[1]

you missed this part i think

conn = mysql.connector.MySQLConnection(host='localhost',port='8051',
                                       database='example',
                                       user='root',
                                       password='tiger')
cursor = conn.cursor()
if conn.is_connected():
    print('Connected to MySQL database')
cursor.execute(""" SELECT * FROM album """)
# fetch all of the rows from the query
data = cursor.fetchall ()

# print the rows
for row in data :
    print row[1]

Solution 2:[2]

import mysql.connector
from mysql.connector import Error

try:
    connection = mysql.connector.connect(host='localhost', database='example', user='root', password='tiger')
    sql_select_Query = "SELECT * FROM album"
    cursor = connection.cursor()
    cursor.execute(sql_select_Query)
    records = cursor.fetchall()
    print("Total number of rows in album is: ", cursor.rowcount)
    print("\nPrinting each album record")
    for row in records:
        print("Id = ", row[0], )
        print("Name = ", row[1], "\n")
        # print("Price  = ", row[2])
        # print("Purchase date  = ", row[3], "\n")
except Error as e:
    print("Error reading data from MySQL table", e)
finally:
if connection.is_connected():
    connection.close()
    cursor.close()
    print("MySQL connection is closed")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 mahesh chougule