1、基本操作
# -*- coding: utf-8 -*-
import sqlite3
def mykey(x):
return x[3]
conn=sqlite3.connect("d:\\demo\\my_db.db")
# a char , b int , c real 表示該表有三個字段,
# a 是字元串類型, b 是整數類型, c 是實數類型。
conn.execute( sql )
cs = conn.cursor()
#cs.execute("delete from mytb where a='張三' ")
cs.execute("delete from mytb ")
#删除所有記錄
'''''
cs.execute( "insert into mytb ( a,b,c,d ) values('zhang san',25, 120, '2014-03-04')" )
cs.execute( "insert into mytb ( a,b,c,d ) values( 'wang wu',24, 110, '2014-05-01')" )
cs.execute( "insert into mytb ( a,b,c,d ) values( 'li si',23, 130, '2014-04-06')" )
'''
#批量注入,batchdata是一個清單,清單裡每一個元素都是一個元組
batchdata=[('zhang san',25, 120, '2014-03-04'),
( 'wang wu',24, 110, '2014-05-01'),
( 'li si',23, 130, '2014-04-06')]
cs.executemany('insert into mytb values (?,?,?,?)',batchdata)
conn.commit() #将加入的記錄儲存到磁盤,非常重要!
cs.execute("select name, sql from sqlite_master where type='table'")
recs = cs.fetchall( )
print ( recs )
cs.execute( "select * from mytb ")#打開資料表
recs = cs.fetchall()#取出所有記錄
print ( "there is ", len(recs)," notes." )
print recs
recs.sort(key = mykey)
print recs
cs.close()
conn.close()
以上代碼參考python中使用sqlite資料庫簡明教程,有少量改動
最新内容請見作者的github頁:http://qaseven.github.io/