Python MySQL Example

Do you like this?

This is a quick tutorial on how to connect to MySQL Server using Python.


Firstly, you have to get MySQLdb set up on your computer. If you are running a Linux computer, you can simply use the following command:

sudo apt-get install python-mysqldb
If you are running a Windows computer, you can download an executable installer for setting it up from

Following is an example on how to connect to MySQL server after getting username and password from a command line:
import getpass
import MySQLdb

host= "localhost"
db_name= 'your-db-name'


def login():
    username= raw_input("Enter Username:")        
    password = getpass.getpass("Enter your password:")
    return username, password

def connect_db(username, password):
    db = MySQLdb.connect(host= host, # your host, usually localhost
                     user=username, # your username
                      passwd=password, # your password
                      db= db_name) # name of the data base
    return db

def main():
    username, password = login()
    db = connect_db(username, password)
    # you must create a Cursor object. It will let
    #  you execute all the query you need
    cur = db.cursor()

    # Use all the SQL you like
    cur.execute("SELECT * FROM accounts")
    # print all the first cell of all the rows
    for row in cur.fetchall() :
        print row[0]

if __name__ == "__main__":

comments powered by Disqus