Newbie needs Help

len lsumnler at gmail.com
Wed Aug 16 22:59:11 EDT 2006


Hi all

I am writing a python program that inserts records into a database on
XP using mxODBC.

I need to write a section of code which will create the following SQL
command as an example;

INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')

This statement will be built up using the following code;

import mx.ODBC
import mx.ODBC.Windows
def insertFromDict(table, dict):
    """Take dictionary object dict and produce sql for
    inserting it into the named table"""
    sql = 'INSERT INTO ' + table
    sql += ' ('
    sql += ', '.join(dict)
    sql += ') VALUES ('
    sql += ', '.join(map(dictValuePad, dict))     # ??? this code does
NOT format correctly
    sql += ')'
    return sql

def dictValuePad(key):                                # ??? this code
does Not format correctly
    return "'" + str(key) + "'"

db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
c = db.cursor()
insert_dict = {'state':'IL', 'name':'Illinois'}
sql = insertFromDict("statecode", insert_dict)
print sql
c.execute(sql)

I copied this code off of ASP and I sure it worked for his particular
circumstance but I need to format up the VALUE clause just a bit
different.

I will be working from a dictionary which will be continualy update in
another part of the program and this code is working.

Len Sumnler




More information about the Python-list mailing list