unicode and mysql

Skip Montanaro skip at pobox.com
Mon Feb 23 17:55:35 EST 2004


    Ilya> I'm having a problem inserting into a mysql database (its not the
    Ilya> mysql, its the encoding of the query sting), could someone point
    Ilya> me in the right direction. The code resembles the following:

    Ilya> text1=hdtext.encode("utf-8")  #this is acquired earlier in the script
    Ilya> string1="just testing"

    Ilya> #this first one would work fine
    Ilya> cursor.execute("insert into table1 (col1) values (%s)" %(text1))
    Ilya> #the next one works too
    Ilya> cursor.execute("insert into table1 (col2) values ('%s')" %(string1))

    Ilya> #however what i need to work is the following
    Ilya> cursor.execute("insert into table1 (col1,col2) values (%s,'%s')" 
    Ilya> % (text1,string1)

Let your database module (presumably MySQLdb) do the encoding for you:

    cursor.execute("insert into table1 (col1,col2) values (%s, %s)",
                   (text1, string1))

Skip




More information about the Python-list mailing list