MySQLdb, lots of columns and newb-ness
Todd Neal
tolchz at gmail.com
Tue Dec 19 22:34:58 EST 2006
Andrew Sackville-West wrote:
>
> I can successfully connect to mysql and do stuff to my tables my
> specific problem is how to efficiently put those 132 fields into the
> thing. All I have been able to figure out is really ugly stuff like:
> build the mysql statement out of various pieces with appropriate
> commas and quote included. stuff like (not tested)
>
I just started looking into Python myself, so someone can probably
clean this up or suggest a better way, but this may work:
import MySQLdb
fields = ["field1\r\n","field2\r\n","field3\r\n"]
def escapeAndQuote(x):
return "\"%s\"" % MySQLdb.escape_string(x)
values = ", ".join([escapeAndQuote(f[:-2]) for f in fields])
q = "insert into daily values(%s)" % values
In testing I got:
>>> fields = ["field1\r\n","field2\r\n","field3\r\n"]
>>> values = ", ".join([escapeAndQuote(f[:-2]) for f in fields])
>>> values
'"field1", "field2", "field3"'
>>> q = "insert into daily values(%s)" % values
'insert into daily values("field1", "field2", "field3")'
Todd
More information about the Python-list
mailing list