How to connect to MySQL database and fetch data in python (using MySQLdb)
0
1446
Installation
For MySQL you need to install external python module.
To install
For Windows user, you can get an exe of MySQLdb.
For Linux, this is a casual package (python-mysqldb). (You can use sudo apt-get install python-mysqldb (for debian based distros), yum install MySQL-python (for rpm-based), or dnf install python-mysql (for modern fedora distro) in command line to download.)
For Mac, you can install MySQLdb using Macport.
import MySQLdb
db = MySQLdb.connect(host="localhost", # your hostname, usually localhost
user="python", # your username of DB
passwd="easy", # your password of DB
db="pe_db") # name of the data base on MySQL
# you must create a Cursor object. It will let
# you execute all the queries you need
cursor = db.cursor()
# Use all the SQL you like
cursor.execute("SELECT * FROM YOUR_TABLE_NAME")
# print all the first cell of all the rows
for row in cursor.fetchall():
print row[0] # This will print the first column value of the table row, yyou can print/fetch row[1], row[2] depending on number of columns
db.close()
Comment here