PythonMySQL

From XPUB & Lens-Based wiki

You'll need the "MySQLdb" library installed.

Connecting to MySQL

If you put this function in a file (say "settings.py"), you can easily import if from different scripts... and also you only need to change the login data in one location (useful for local vs. server-based testing).

import MySQLdb

def connect_db():
    host_name = "localhost"
    db_name = "dbname"
    user_name = "dbuser"
    password = "dbpass"
    
    try:
        conn = MySQLdb.connect (db = db_name,
                                host = host_name,
                                user = user_name,
                                passwd = password)
        return conn
    except MySQLdb.Error, e:
        print "Cannot connect to server"
        print "Error code:", e.args[0]
        print "Error message:", e.args[1]
        sys.exit(1)