Python sqlite3數據庫是一款很是小巧的內置模塊,它使用一個文件存儲整個數據庫,操做十分方便,相比其餘大型數據庫來講,確實有些差距。可是在性能表現上並不遜色,麻雀雖小,五臟俱全,sqlite3實現了多少sql-92標準,好比說transaction、trigger和複雜的查詢等。
Python的數據庫模塊有統一的接口標準,因此數據庫操做都有統一的模式(假設數據庫模塊名爲db):sql
1. 用db.connect建立數據庫鏈接,假設鏈接對象爲conn數據庫
2. 若是該數據庫操做不須要返回結果,就直接使用conn.execute查詢,根據數據庫事物隔離級別的不一樣,可能修改數據庫須要conn.commitapp
3. 若是須要返回查詢結果則用conn.cursor建立遊標對象cur,經過cur.execute查詢數據庫,cursor方法有fetchall、fetchone、fetchmany返回查詢結果,根據數據庫事物隔離級別不一樣,可能修改數據庫須要coon.commit性能
4. 關閉cur.closefetch
#coding=utf-8 import sqlite3 conn = sqlite3.connect("sqlite.db") #建立sqlite.db數據庫 print ("open database success") conn.execute("drop table IF EXISTS student") query = """create table IF NOT EXISTS student( customer VARCHAR(20), produce VARCHAR(40), amount FLOAT, date DATE );""" conn.execute(query) print ("Table created successfully") #在表中插入數據 ''' 方法1 ''' #data = '''INSERT INTO student(customer,produce,amount,date)\ # VALUES("zhangsan","notepad",999,"2017-01-02")''' #conn.execute(data) #data = '''INSERT INTO student(customer,produce,amount,date)\ # VALUES("lishi","binder",3.45,"2017-04-05")''' #conn.execute(data) #conn.commit() ''' 方法2 ''' statement = "INSERT INTO student VALUES(?,?,?,?)" data = [("zhangsan","notepad",999,"2017-01-02"),("lishi","binder",3.45,"2017-04-05")] conn.executemany(statement, data) conn.commit() curson = conn.execute("select * from student") conn.commit() print (curson) rows = curson.fetchall() print (rows) conn.close()
'''將csv數據導入數據庫''' import sys import csv import sqlite3 #解析csv文件 def parsecsvFile(filepath): header = None data = [] with open(filepath, 'r') as csvfile: filereader = csv.reader(csvfile) header = next(filereader) #print (header) for row in filereader: data.append(row) #print (data) return header,data #使用sqlite3寫數據庫 def initdb(header, data): conn = sqlite3.connect("sqlite.db") print ("connect database success") conn.execute("drop table IF EXISTS student") conn.commit() query = '''create table IF NOT EXISTS student(\ Supplier Name VARCHAR(32), Invoice Number VARCHAR(16), Part Number VARCHAR(16), Cost VARCHAR(16), Purchase Date DATE);''' conn.execute(query) conn.commit() statement = "INSERT INTO student VALUES(?,?,?,?,?)" conn.executemany(statement, data) conn.commit() curson = conn.execute("select * from student") conn.commit() print (curson) rows = curson.fetchall() print (rows) conn.close() return rows #根據數據庫內容寫csv文件 def wirtecsvfile(writefilepath, header, data): with open(writefilepath, 'a+') as writefile: writer = csv.writer(writefile, delimiter=",") writer.writerow(header) for row in data: writer.writerow(row) if __name__ == "__main__": readfilepath = sys.argv[1] writefilepath = sys.argv[2] header,data = parsecsvFile(readfilepath) rows = initdb(header, data) wirtecsvfile(writefilepath, header, rows)