Python read data from MySQL database

The following code can read data from MySQL database.

import MySQLdb
 
# Open database connection
db = MySQLdb.connect("localhost","username","password","DBName")
 
# prepare a cursor object using cursor  method
cursor = db.cursor() 
 
sql = "select * from table1"
cursor.execute(sql)
results = cursor.fetchall() 
for row in results:
    print row[0]
 
# disconnect from server
db.close()

Leave a Comment