#实例:用数据库存储日记,实现日记本功能
#流程
#创建数据库
1 #coding:utf-8 2 import sqlite3 3 connect=sqlite3.connect('test.db') 4 connect.close()
#效果
#用sqlite3模块对数据库进行操作
1 #coding:utf-8 2 import sqlite3 3 #创建数据库 4 connect=sqlite3.connect('test.db') 5 cursor = connect.cursor() 6 #为了多次执行该段程序所以在开头删除表diary1 7 cursor.execute("drop table diary1") 8 9 #创建表 10 cursor.execute("create table diary1 (id integer primary key autoincrement,title text,content text)") 11 #插入数据,id自增所以可以写null 12 cursor.execute("insert into diary1 values (null,'title1','content1')") 13 #插入数据 14 cursor.execute("insert into diary1(title,content) values ('title2','content2')") 15 16 #查询表中所有数据 17 for row in cursor.execute("select * from diary1"): 18 print row 19 print '*******增*******' 20 21 22 #删除id为1的数据 23 cursor.execute("delete from diary1 where id=1") 24 for row in cursor.execute("select * from diary1"): 25 print row 26 print '******删除*******' 27 28 #修改数据 29 cursor.execute("update diary1 set title='title0',content='content0' where id =2") 30 for row in cursor.execute("select * from diary1"): 31 print row 32 print '*****改******' 33 34 #一次性插入多条数据 35 items=[('title0','content0'),('title1','content1'),('title2','content2')] 36 cursor.executemany("insert into diary1 (title,content) values(?,?)",items) 37 for row in cursor.execute("select * from diary1"): 38 print row 39 print "******插入多条数据******" 40 41 #查询数据 42 print '查询数据' 43 cursor.execute("select * from diary1 where id=4") 44 print cursor.fetchall() 45 46 cursor.execute("select * from diary1 where content='content0'") 47 print cursor.fetchall() 48 49 #关闭游标和数据库 50 cursor.close() 51 connect.close()
#效果
#注意到在python的sqlite3模块中,数据库中的每个记录都是以一个tuple的形式存储
#表中数据除了主键外其他字段的值都可以重复
#获取当前数据库中的所有表
1 #coding:utf-8 2 import sqlite3 3 connect = sqlite3.connect("test.db") 4 cursor = connect.cursor() 5 6 7 8 #插入记录,参数为表名(str),数据(元组) 9 def insertData(table,tup): 10 global cursor 11 global connect 12 sql="insert into "+table+"(title,content) values (?,?)" 13 cursor.execute(sql,tup) 14 #对数据库操作事务的提交 15 connect.commit() 16 17 #删除特定id的记录 18 def deleteData(name,id): 19 global cursor 20 global connect 21 sql="delete from "+name+" where id="+str(id) 22 cursor.execute(sql) 23 connect.commit() 24 25 #根据id修改数据,参数为表名,id(整型),数据(元组) 26 def updateData(name,id,tup): 27 global cursor 28 global connect 29 sql="UPDATE "+name+" SET title='"+tup[0]+"',content='"+tup[1]+"' WHERE id="+str(id) 30 cursor.execute(sql) 31 connect.commit() 32 33 #根据id查找数据,参数为表名(str),id 34 def searchData(name,id): 35 #为什么这里又不需要global connect 36 global cursor 37 sql="select * from "+name+" where id="+str(id) 38 cursor.execute(sql) 39 #cursor.fetchall()和cursor.fetchone()区别? 40 print u"要查找的数据为:",cursor.fetchone() 41 42 43 44 insertData('mydiary',('title0','content0')) 45 updateData("mydiary",2,('title3','content3')) 46 #deleteData('mydiary',1) 47 insertData('mydiary',('title9','content9')) 48 searchData("mydiary",6)