[Tutor] MySQL Connection Function

Don Parris webdev at matheteuo.org
Wed Jun 22 20:37:10 CEST 2005

On Tue, 21 Jun 2005 19:13:43 -0400
Python <python at venix.com> wrote:

Alright, I've had time to play with this and wanted to be sure I understand
this well.  It works, so I understand enough to make it work.  However, I
see a difference between your code and mine that makes me think I've missed
something other than the relationship between the cursor & the connection


> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
> #! /usr/bin/python
> # sqlconnect.py
> import MySQLdb as SQLdb

I didn't see anything in the tutorial about the import as.  Is this simply
assigning the module a variable name?

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

O.k., I was attempting to return "Con", not sql.connect() in my function.  I
think that's where part of my problem was.

> 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()

As is, I can copy/paste the 4 lines above into each function I've defined,
and it works like a charm. What I would like now, is to use this like so:

### function for the cursor ### 
def get_Curs():  
    curs = conn.Cursor()
    results = curs.fetchall()

Would I use curs.execute as an argument to get_Curs()?  And would I then
feed sqlCmd into mbr_Phone(sqlCmd)?

### Run get_Curs() for this query and give the user the results.###
def mbr_Phone():  # how to get the cursor?
    get_Curs()    # 
    # Make SQL string and execute it.
    sqlCmd = "SELECT fst_name, lst_name, hphn FROM person\
            order by lst_name"
   print 'Phone List'
    for record in Results:
        print record[0] , '', record[1], '\t', record[2]

def a_Query(sqlCmd):
    code for a_Query

def other_Query(sqlCmd):
    code for other_Query
Kind of like this, anyway.  Thanks for your patience. :)

evangelinux    GNU Evangelist
http://matheteuo.org/                   http://chaddb.sourceforge.net/
"Free software is like God's love - you can share it with anyone anytime

More information about the Tutor mailing list