How to retrieve data from a MySQL table through Python code?
How to retrieve data from a MySQL table through Python code?
Share
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Aviance School is one of the largest web solutions platform in India for developers to learn and share their programming knowledge and build their careers.
You can get data OR query data from a MySQL database in Python by using MySQL Connector/Python API such as fetchone() OR fetchall()
Fetch a single row:
row = cursor.fetchone ()
Fetch multiple rows:
data = cursor.fetchall ()
Example code:
import MySQLdb
import sys
connection = MySQLdb.connect (host = "192.168.1.1", user = "root", passwd = " " , db = "data_wirehouse")
cursor = connection.cursor ()
cursor.execute ("select firstname,lastname from user_master")
data = cursor.fetchall ()
for row in data :
print row[0], row[1]
cursor.close ()
connection.close ()
sys.exit()