Python sqlite3數據庫是一款非常小巧的內置模塊,它使用一個文件存儲整個數據庫,操作十分方便,相比其他大型數據庫來說,確實有些差距。但是在性能表現上並不遜色,麻雀雖小,五臟俱全,sqlite3實現了多少sql-92標准,比如說transaction、trigger和復雜的查詢等。
描述
Python的數據庫模塊有統一的接口標准,所以數據庫操作都有統一的模式(假設數據庫模塊名為db):
1. 用db.connect創建數據庫連接,假設連接對象為conn
2. 如果該數據庫操作不需要返回結果,就直接使用conn.execute查詢,根據數據庫事物隔離級別的不同,可能修改數據庫需要conn.commit
3. 如果需要返回查詢結果則用conn.cursor創建游標對象cur,通過cur.execute查詢數據庫,cursor方法有fetchall、fetchone、fetchmany返回查詢結果,根據數據庫事物隔離級別不同,可能修改數據庫需要coon.commit
4. 關閉cur.close
sqlite3基本操作用例
#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()
sqlite3 csv->db->csv
'''將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)
