Re: mysql insert with tuple

Discussion in 'Python' started by Hans Mulder, Nov 21, 2012.

  1. Hans Mulder

    Hans Mulder Guest

    On 21/11/12 18:19:15, Christian wrote:
    > Hi ,
    >
    > my purpose is a generic insert via tuple , because the number of fields and can differ. But I'm stucking .
    >
    > ilist=['hello',None,7,None,None]
    >
    > #This version works, but all varchar fields are in extra '' enclosed.
    > con.execute(""" INSERT INTO {} VALUES %r; """.format(table) , (tuple(ilist),))
    >
    > #This produce (1054, "Unknown column 'None' in 'field list'"),
    > #but without None values it works.
    > con.execute(""" INSERT INTO {} VALUES %r; """.format(table) % (tuple(ilist),))


    How about:

    con.execute("""INSERT INTO {} VALUES ({})"""
    .format(table, ",".join("%s" for _ in ilist)), ilist)

    Or perhaps break it down into smaller steps:

    bind_variables = ",".join("%s" for _ in ilist))
    query = "INSERT INTO {} VALUES ({})".format(table, bind_variables)
    con.execute(query, ilist)


    Hope this helps,

    -- HansM
     
    Hans Mulder, Nov 21, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Michal Mikolajczyk
    Replies:
    1
    Views:
    839
    Larry Bates
    Apr 20, 2004
  2. Jeff Epler
    Replies:
    0
    Views:
    1,046
    Jeff Epler
    Apr 20, 2004
  3. Bill Scherer
    Replies:
    0
    Views:
    638
    Bill Scherer
    Apr 20, 2004
  4. Gregor Horvath

    Why tuple with one item is no tuple

    Gregor Horvath, Mar 15, 2005, in forum: Python
    Replies:
    37
    Views:
    868
    Antoon Pardon
    Mar 30, 2005
  5. Steve
    Replies:
    1
    Views:
    1,005
    Fredrik Lundh
    Dec 13, 2005
Loading...

Share This Page