Python Code to Select Data from MySQL
As earlier we have inserted data to MySQL Data Tables using Python Code. To Select the data from MySQL Tables we have to follow the same procedure:
connection = mysql.connector.connect(host='localhost',
database='dbphpdemo',
user='root',
password='')
mysql.connector.connec() function will connect to your MySQL Server, You must be sure that Username,Passwords are correct the same user has access to the database and MySQL Server is running. To use this function you have to import mysql.connector
query = "select * from tblwebsitedetails"
cursor = connection .cursor()
cursor.execute(query)
records = cursor.fetchall()
Now open a cursor as earlier example and execute query. To get all the records based on query, cursor.fetchall() function will get records to ‘records’ variable in our case. Entire Code is like:
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='dbphpdemo',
user='root',
password='')
query = "select * from tblwebsitedetails"
cursor = connection .cursor()
cursor.execute(query)
records = cursor.fetchall()
print("Total number of rows :", cursor.rowcount)
print ("Getting Rows By Rows")
for row in records:
print("Id = ", row[0], )
print("Website = ", row[1])
print("Details = ", row[2])
print("Rank = ", row[4])
print("Start Date = ", row[3], "\n")
cursor.close()
except Error as e :
print ("Error while connecting to MySQL", e)
finally:
#closing database connection.
if(connection .is_connected()):
connection.close()
print("MySQL connection is closed")
Here we have used the same database that we have applied in our earlier example.