CSV2SQLなるものを見つけた。


題通りなんか見つけた。とりあえず参考にしながら自分でもCSV2SQL for Pythonを作ってみようと思う。

import sqlite3
import csv 
# SQLite内のデータはutf-8を想定
def sqlite2csv(db_name, table_name, out_filename):
  dbh = sqlite3.connect(db_name)
  writer = csv.writer(file(out_filename, 'w'))
  for row in dbh.execute('SELECT * FROM %(table_name)s' % locals()):
    writer.writerow([col.encode('utf-8') if isinstance(col, unicode) else col for col in row])
  dbh.close()
 
# csvのセパレータはカンマを想定
def csv2sqlite(db_name, table_name, in_filename):
  dbh = sqlite3.connect(db_name)
  reader = csv.reader(open("import.csv", "rb"))
  for row in reader:
    ph = "?," * (len(row) - 1) + "?"
    dbh.execute("INSERT INTO %(table_name)s VALUES(%(ph)s)" % locals(), tuple(row))
  dbh.commit()
  dbh.close()

引用:http://taichino.com/engineer-life/database/1016