How to retrieve data from a MySQL table through Python code?

How to retrieve data from a MySQL table through Python code?

Senior Developer Asked on March 21, 2017 in PYTHON.
Add Comment
1 Answer(s)

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()

Team Leader Answered on December 5, 2017.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.