MySQLdb syntax issues - HELP

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Dec 16 15:13:27 EST 2007


Luke a écrit :
> Im very new to SQL in general, let alone coding it into python. I can
> interact with a MySQL database just fine for the most part, but im running
> into some problems here... 
(snip)
> 
> -------------------------------------------------
> 
> def NewChar():
>     """ NewChar() -
>     Call this function to begin new character generation. 
>     
>     At this time it is the only function you need to call from the
> NewCharacter module.
>     
>     It takes no arguments.
>     
>     """
>     CharAccount = NewAccount()
(snip)

>     
>     cursor.execute("""
>         CREATE TABLE %s
>         ( 
>          name     CHAR(40),
>          gender   CHAR(40),
>          job      CHAR(40),
>          level    TEXT,
>          str      TEXT,
>          dex      TEXT,
>          intel    TEXT,
>          cha      TEXT,
>          luc      TEXT
>         ) 
>     """ % CharAccount)

Err... Are you sure you want a new table here ?

>     CharInfo = (CharAccount, CharName, CharGender, CharJob, CharLevel,
> Strength, Dexterity, Inteligence, Charm, Luck)
>     
>     cursor.execute("""
>        INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
>        VALUES
>         (%s, %s, %s, %s, %s, %s, %s, %s, %s)
>     """, (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
> Dexterity, Inteligence, Charm, Luck))
>     
(snip)
> The part that keeps getting me errors is:
> 
> -------------------------------------------------------
> 
>     cursor.execute("""
>        INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
>        VALUES
>         (%s, %s, %s, %s, %s, %s, %s, %s, %s)
>     """, (CharAccount, CharName, CharGender, CharJob, CharLevel, Strength,
> Dexterity, Inteligence, Charm, Luck))
> 
> -------------------------------------------------------
> 
> i have tried various ways to do this string insertion, and i keep getting
> errors. it seems that MySQLdb doesnt like me assigning a string to the
> table name if im going to assign more to values... 

Your problem comes from confusion between Python's string formating 
system and db-api query arguments system - which sometimes (as here) use 
the same placeholder mark.

What you want here is:

sql = """
INSERT INTO %s (name, gender, job, level, str, dex, intel, cha, luc)
VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s)
""" % CharAccount

cursor.execute(sql,  (CharName, CharGender, CharJob, CharLevel, 
Strength, Dexterity, Inteligence, Charm, Luck))




More information about the Python-list mailing list