mysql insert with tuple
Christian
mining.facts at gmail.com
Thu Nov 22 02:56:23 EST 2012
Am Mittwoch, 21. November 2012 20:49:14 UTC+1 schrieb Hans Mulder:
> 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
Thank you both!. However, for future issues I'll take Chris advise about a ORM into account . It's only a sort of data crunching (offline), so SQL Injection isn't a problem.
More information about the Python-list
mailing list