Python语言操作SQLite3数据库的基本流程:
1、导入相关库或模块(SQLite3)
2、使用connect()连接数据库并获取数据库连接对象,它提供了以下方法:
.cutsor()方法来创建一个游标对象
.commit()方法来处理事务提交
.rollback()方法来处理事务回滚
.close()方法来关闭一个数据库连接
3、使用con.cursor()获取游标对象
4、使用游标对象的方法(execute() executemany() fetchall()等)来操作数据库
实现插入、修改和删除操作,并查询获取显示相关的记录。在Python程序中,连接函数
sqlite3.connect()有如下两个常用参数
database: 表示要访问的数据库名
timeout:表示访问数据的超时设定
5、使用close()关闭游标对象和数据库连接,数据库操作完成后,必须及时调用其close()方法关闭数据库连接
这样做的目的是减轻数据库服务器的压力
使用SQLite3创建表
使用sqlite3模块的connect方法来创建或打开数据库,需要指定数据库路径,不存在则创建一个新的数据库
'''
1、导入sqlite3模块
2、创建连接sqlite3.connect()
3、创建游标对象
4、编写创建表的sql语句
5、执行sql语句
6、关闭连接
'''
import sqlite3
#创建连接
con=sqlite3.connect('D:/python/demo.db')
#创建游标对象
cur=con.cursor()
#编写创建表的sql语句
sql='''create table t_person(
pno INTEGER primary key autoincrement,
pname VARCHAR not null,
age INTEGER
)'''
try:
# 执行sql语句
cur.execute(sql)
print("创建表成功")
except Exception as e:
print(e)
print("创建表失败")
finally:
cur.close()
#关闭游标
con.close()
#关闭连接
使用SQLite插入数据
调用游标对象的execute执行插入的sql,使用executemany()执行多条
sql语句,使用executemany()比循环使用excute()执行多条sql语句效率高
#操作插入一条数据
#导入模块
import sqlite3
#创建连接
con=sqlite3.connect('D/python/demo.db')
#创建游标对象
cur=con.cursor()
#编写插入sql
sql='insert into t_person(pname,age) values(?,?)'
try:
#执行sql
cur.execute(sql,('张三',24))
#提交事务
con.commit()
print('插入数据成功')
except Exception as e:
print(e)
con.rollback()
print('插入数据失败')
finally:
#关闭游标连接
cur.close()
#关闭数据库连接
con.close()
使用SQLite3查询数据
查询数据,游标对象提供了fetchall()和fetchone()方法。
fetchall()方法获取所有数据,返回一个列表。fetchall()方法获取其中一个结果,返回一个元组
#导入模块
import sqlite3
#创建连接
con=sqlite3.connect('D:/python/demo.db')
#创建游标对象
cur=con.cursor()
#创建查询sql
sql='select * from t_person'
try:
cur.execute(sql)
#获取结果集
person_all=cur.fetchall()
#print(person_all)
for person in person_all:
print(person)
#获取一条数据
person=cur.fetchone()
print(person)
except Exception as e:
print(e)
print('查询所有数据失败')
finally:
#关闭游标
cur.close()
#关闭连接
con.close()
#修改数据
#导入模块
import sqlite3
#创建连接
con=sqlite3.connect('D:/python/demo.db')
#创建游标对象
cur=con.cursor()
#编写修改的SQL语句
sql='update t_person set pname=? where pno=?'
#执行sql
try:
cur.execute(sql,('小张',1))
con.commit()
print('创建成功')
except Exception as e:
print(e)
print('修改失败')
con.rollback()
finally:
#关闭游标
cur.close()
#关闭连接
con.close()
#删除数据
#导入数据库
import sqlite3
#创建连接
con=sqlite3.connect('D:/python/demo.db')
#创建游标对象
cur=sqlite3.cursor()
#编写删除数据的SQL语句
sql='delete from t_person where pno=?'
#执行sql
try:
cur.execute(sql,(1,)) #(1)并不能识别为元组
#提交事务
con.commit()
print('删除成功')
except Exception as e:
print(e)
print('删除失败')
con.rollback()
finally:
#关闭连接
con.close()