Skip to content

Instantly share code, notes, and snippets.

@yuitest
Created April 2, 2014 23:59
Show Gist options
  • Save yuitest/9945758 to your computer and use it in GitHub Desktop.
Save yuitest/9945758 to your computer and use it in GitHub Desktop.
table を無理やり突っ込む
# coding: utf-8
from __future__ import unicode_literals, print_function
import sqlite3
import itertools
import types
import uuid
def table(connection, iterable, name=None):
if name is None:
name = '__{}'.format(unicode(uuid.uuid4()).replace('-', ''))
iterable = (x for x in iterable)
r = next(iterable)
if not isinstance(r, (types.ListType, types.TupleType)):
r = (r, )
iterable = ((x, ) for x in iterable)
fields = ', '.join('f{}'.format(i) for i, _ in enumerate(r))
iterable = itertools.chain((r, ), iterable)
insertsql = 'INSERT INTO {} VALUES ({})'.format(
name, ', '.join('?' * len(r)))
connection.execute('CREATE TEMPORARY TABLE {} ({})'.format(name, fields))
connection.executemany(insertsql, iterable)
return name
if __name__ == '__main__':
con = sqlite3.connect('x.db')
table(con, ((1, 2), (3, 4)), 'testing')
print(list(con.execute('SELECT * FROM testing')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment