操做數據庫:sql
>>> import sqlite3 # 若是文件不存在,會自動在當前目錄建立: >>> conn = sqlite3.connect('test.db') >>> cursor = conn.cursor() >>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))') >>> cursor.execute(r'insert into user (id, name) values (\'1\', \'Michael\')') # 執行insert,update,delete語句時,經過rowcount得到影響的行數: >>> cursor.rowcount 1 >>> cursor.close() >>> conn.commit() >>> conn.close()
執行查詢:數據庫
>>> conn = sqlite3.connect('test.db') >>> cursor = conn.cursor() >>> cursor.execute('select * from user where id=?', ('1',)) >>> values = cursor.fetchall() # 結果集是一個list,每一個元素都是一個tuple,對應一行記錄 >>> values [('1', 'Michael')] >>> cursor.close() >>> conn.close()