时间:2021-07-01 10:21:17 帮助过:13人阅读
关于Python操作sqlite3的相关核心代码,如下所示:
创建数据表
1 def createDb(): 2 """创建db数据表""" 3 sql = ‘‘‘ 4 create table person ( 5 id integer primary key autoincrement not null, 6 name varchar not null, 7 age integer 8 ) 9 ‘‘‘ 10 executeSql(sql)View Code
插入语句
1 def insertData(name, age): 2 """插入数据""" 3 sql = ‘insert into person (name,age)values(?,?)‘ 4 executeSql(sql, (name, age))View Code
update语句
1 def updateData(id, name, age): 2 """通过ID进行修改语句""" 3 sql = ‘update person set name=?,age =? where id=?‘ 4 executeSql(sql, (name, age, id))View Code
delete语句
1 def deleteData(id): 2 """通过ID删除数据""" 3 sql = ‘delete from person where id=?‘ 4 executeSql(sql, (id,))View Code
上面的语句都调用统一的executeSql方法,如下所示:
1 def executeSql(sql, *args): 2 """执行更新语句""" 3 conn = sqlite3.connect(dbfile) 4 cur = conn.cursor() 5 try: 6 cur.execute(sql, *args) 7 conn.commit() 8 print(‘执行成功,影响行数:‘, cur.rowcount) 9 except Exception as e: 10 conn.rollback() 11 print(e) 12 print(‘执行失败‘) 13 finally: 14 cur.close() 15 conn.close()View Code
查询语句(无条件查询)
1 def queryData(): 2 """查询语句""" 3 sql = ‘select id,name,age from person ‘ 4 executeQuerySql(sql)View Code
查询语句(条件查询)
1 def queryDataById(id): 2 """通过id进行查询""" 3 sql = ‘select id,name,age from person where id = ? ‘ 4 executeQuerySql(sql, (id,))View Code
上面的查询语句,都调用统一的executeQuerySql方法,如下所示:
1 def executeQuerySql(sql, *args): 2 """执行查询语句,可带参数""" 3 conn = sqlite3.connect(dbfile) 4 cur = conn.cursor() 5 try: 6 cur.execute(sql, *args) 7 persons = cur.fetchall() 8 for p in persons: 9 print(‘当前行信息如下:‘) 10 print(p) # 返回的是一个元组tuple 11 print(‘查询成功‘) 12 except Exception as e: 13 print(e) 14 print(‘查询失败‘) 15 finally: 16 cur.close() 17 conn.close()View Code
关于本例子的执行源码,可通过链接进行下载,如下所示:
源码链接
业精于勤,荒于嬉;行成于思,毁于随!!!
Python之Sqlite3数据库基本操作
标签:none 游标对象 mil 关闭 creat 条件 hide file pen