1. 程式人生 > >使用python將csv資料匯入到sqlite中

使用python將csv資料匯入到sqlite中

指令碼如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import sqlite3
def  dataImport(csvpath,dbpath,tablename):
    reader = csv.DictReader(open(csvpath,"rb"),delimiter=',',quoting=csv.QUOTE_MINIMAL)
    conn = sqlite3.connect(dbpath)
    # shz: fix error with non-ASCII input
    conn.text_factory = str
    c = conn.cursor()
    create_query = 'CREATE TABLE '+tablename +' ("cn" TEXT,"en" TEXT,"lat" DOUBLE,"lon" DOUBLE,"points" DOUBLE,"count" INTEGER,"intro" TEXT,"photo" TEXT,"url" TEXT,"content" TEXT)' 
    c.execute(create_query)
    for row in reader:
        print row
        to_db = [row['cn'], row['en'],row['lat'],row['lon'],row['points'],row['count'],row['intro'],row['photo'],row['url'],row['content']]
        c.execute('INSERT INTO '+tablename+' (cn, en, lat,lon,points,count,intro,photo,url,content) VALUES (?, ?, ?,?, ?, ?,?, ?, ?,?);', to_db)
    conn.commit()


檢視原文:http://www.giser.net/?p=1337