Python:【学习笔记】SQLite数据库的使用

1 数据库的基础知识

1.1数据表

一个数据库可以包含多个数据表,数据表是一系列二维数组的结合,存储和操作数据的逻辑结构。数据表由行和列组成,每一列都由字段值和字段名组成。

2 Python使用数据库过程

2.1 创建SQLite数据库文件

# 导入模块
import sqlite3

# 创建连接对象
conn = sqlite3.connect('mrsoft.db')

# 创建游标对象
conn.cursor()

# 执行SQL语句
cursor.execute('create table user(id int(10) primary key, name varchar(20))')

# 关闭游标
cursor.close()

# 关闭连接
conn.close()

2.2 操作SQLite数据

2.2.1 新增用户数据信息
# 导入模块
import sqlite3

# 创建连接对象
conn = sqlite3.connect('mrsoft.db')

# 创建游标对象
conn.cursor()

# 执行SQL语句
sql = 'insert into user (id, name) values(?, ?)'   # 为了避免cursor注入
cursor.execute(sql, (1, "mrsoft"))       
data = [(2,'andy'), (3, 'kobe'), (4, 'jordan')]
cursor.executemany(sql, data)

# 关闭游标
cursor.close()

# 提交事务
conn.commit()

# 关闭连接
conn.close()
2.2.2 查询用户数据信息
# 导入模块
import sqlite3

# 创建连接对象
conn = sqlite3.connect('mrsoft.db')

# 创建游标对象
conn.cursor()

# 执行SQL语句
sql1 = 'select * from user'
sql2 = 'select * from user where id < 2'    # 有条件的查询
cursor.execute(sql)

result1 = cursor.fetchone()
print(result1)

result2 = cursor.fetchmany(2)
print(result2)

result3 = cursor.fetchall()
print(result3)

# 关闭游标
cursor.close()

# 关闭连接
conn.close()
2.2.3 修改用户信息
# 导入模块
import sqlite3

# 创建连接对象
conn = sqlite3.connect('mrsoft.db')

# 创建游标对象
conn.cursor()

# 执行SQL语句
sql = 'update user set name = ? where id = ?'   # 为了避免cursor注入
cursor.execute(sql, ("Jack", 1))       

# 关闭游标
cursor.close()

# 提交事务
conn.commit()

# 关闭连接
conn.close()
2.2.4 删除用户数据信息
# 导入模块
import sqlite3

# 创建连接对象
conn = sqlite3.connect('mrsoft.db')

# 创建游标对象
conn.cursor()

# 执行SQL语句
sql = 'delete from user where id = ?'  
cursor.execute(sql, (1,)) 
     
cursor.execute('select * from user') 
result = cursor.fetchall()
print(result)

# 关闭游标
cursor.close()

# 提交事务
conn.commit()

# 关闭连接
conn.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值