sqlite讀寫
#coding=utf-8 import sqlite3 import os #創建數據庫和游標 if os.path.exists(' test.db'):conn=sqlite3.connect(' test.db')cur=conn.cursor() else:conn=sqlite3.connect(' test.db')cur=conn.cursor()#創建表 cur.execute('CREATE TABLE IF NOT EXISTS customer (ID VARCHAR(300),NAME VARCHAR(300),''SEX VARCHAR(300),TELEPHONE VARCHAR(300),PRIMARY KEY(ID))') try:#插入數據for t in [('1','alex','man','189'),('2','tom','man','139')]:conn.execute('INSERT INTO customer VALUES(?,?,?,?)',t)#未出錯commit提交后生效conn.commit() except:#出錯,回滾conn.rollback() #關閉游標 cur.close() #關閉數據庫鏈接 conn.close()
使用游標查詢數據庫:
?游標對象有以下的操作:
execute()--執行sql語句? ?
executemany--執行多條sql語句? ?
close()--關閉游標? ?
fetchone()--從結果中取一條記錄,并將游標指向下一條記錄? ?
fetchmany()--從結果中取多條記錄? ?
fetchall()--從結果中取出所有記錄? ?
scroll()--游標滾動
?
1.查詢
cur.execute("select?*?from?customer")
cur. fetchall()
2.修改
cur.execute("update?customer set?sex='women'?where?id?=?1")
cx.commit()
3.刪除
cur.execute("delete?from?customer where?id?=?1")??
conn.commit()
4.打印中文,須依次打印字符串
?for?item?in?cur.fetchall():
???? for?element?in?item:
???????? print?element
參考:
http://www.cnblogs.com/yuxc/archive/2011/08/18/2143606.html
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000