Here is an example of how I use it to build an arbitrary long SQL request
without having to pay for long intermediate strings, both in computation on
memory.
from itertools import chain #, join
def join(sep, iterable):
notfirst=False
for i in iterable:
if notfirst:
yield sep
else:
notfirst=True
yield i
table = 'mytable'
columns=('id', 'v1', 'v2')
values = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
request = ''.join(chain(
('INSERT INTO ', table, '('),
join(', ', columns),
(') VALUES (',),
chain.from_iterable(join(('), (',), (join(', ', ('%s' for v in value))
for value in values))),
(') ON DUPLICATE KEY UPDATE ',),
chain.from_iterable(join((', '), ((c, '=VALUES(', c, ')') for c in
columns))),
))
args = list(chain.from_iterable(values))
print(request)
> INSERT INTO mytable(id, v1, v2) VALUES (%s, %s, %s), (%s, %s, %s), (%s,
%s, %s) ON DUPLICATE KEY UPDATE id=VALUES(id), v1=VALUES(v1), v2=VALUES(v2)
I often had such cases, but ended up using the more costy str.join .
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/4ICYWZK7D22E75MLP76CGDI3O77OML3Q/
Code of Conduct: http://python.org/psf/codeofconduct/