[Tutor] MySQL Connection Function

Python python at venix.com
Wed Jun 22 01:13:43 CEST 2005


As a newbie developer, the easiest way for me to connect to MySQL is to
> just copy & paste the connection commands into each funtion I write. 
> However, I know that's far from ideal, and consumes more time than its
> worth.  I would like to create a MySQL connection function that I can just
> call up whenever I need it from within an other function.

I like to use the following style of code.  Since there will be
passwords, the connection strings should be somewhat protected.  Put
them in a separate file that can be controlled.  Here's my sample code.
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#! /usr/bin/python
# sqlconnect.py
import MySQLdb as SQLdb

db_parms = {
    'regular': {
        'host': 'localhost',
        'user':'regular_user',
        'passwd':'password',
        'db':'some_database',
    },
    'premium': {
        'host':'localhost',
        'user':'premium_user',
        'passwd':'password',
        'db': 'SGSG02',
    },
    "super": {
        'host': 'localhost',
        'unix_socket': '/var/lib/superdb/mysql.sock',
        'user':'super_user',
        'passwd':'password',
        'db':'some_database',
    },
}

def connect( parm_name):
    parms = db_parms[parm_name]
    return SQLdb.connect( **parms)
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Use a dictionary to save the connect parameters.  Different users and
circumstances can require different parameters.  To use this code

import sqlconnect as sql
conn = sql.connect('regular')

# then get a cursor so that you can do something to the database
curs = conn.Cursor()
curs.execute(Some_SQL_Command)
results = curs.fetchall()
curs.close()

Your example code seems to view getting a connection and a cursor as
closely related.  Typically, a connection is kept for the life of the
application process and cursors are created, used, and closed as needed.


-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list