基于python的SQLite数据库增删改查

        与其他数据库管理系统不同,SQLite不是一个客户端/服务器结构的数据库引擎,而是一种嵌入式数据库,他的数据库就是一个文件。SQLite将整个数据库,包括定义、表、索引以及数据本身,作为一个单独的、可跨平台使用的文件存储在主机中。

        python内置了SQLite3,所以,在python中使用SQLite不需要安装任何模块,可以直接使用。

        本文记录了python对SQLite数据库增删改查的代码。代码如下:

import sqlite3

# 连接到SQLite数据库
# 数据库文件是mrsoft.db,如果文件不存在,会自动在当前目录创建
conn = sqlite3.connect('sqlitetest.db')
# 创建一个Cursor
cursor = conn.cursor()
# 执行一条SQL语句,创建user表
cursor.execute('create  table  user (id int(10)  primary key, name varchar(20))')
# 向数据表中新增数据
cursor.execute('insert into user (id, name) values ("1","zhang")')
cursor.execute('insert into user (id, name) values ("2","ren")')
cursor.execute('insert into user (id, name) values ("3","min")')
cursor.execute('insert into user (id, name) values ("4","xiao")')
cursor.execute('insert into user (id, name) values ("5","peng")')
cursor.execute('insert into user (id, name) values ("6","you")')
# 执行查询语句
cursor.execute('select * from user')
# 获取查询结果
result1 = cursor.fetchone()  # 使用fetchone方法查询一条数据
print("fetchone result is:", result1)
result2 = cursor.fetchmany(2)  # 使用fetchmany方法查询多条数据
print("fetchmany(2) result is:", result2)
result3 = cursor.fetchall()  # 使用fetchall方法查询多条数据
print("fetchall result is:", result3)
# 执行查询语句,使用占位符,避免SQL注入
cursor.execute('select * from user where id > ?', (1,))
result3 = cursor.fetchall()
print("id >1 result is:", result3)
# 创建一个Cursor
cursor = conn.cursor()
# 修改用户数据信息
cursor.execute('update user set name = ? where id = ?', ('wang', 1))
# 创建一个Cursor
cursor = conn.cursor()
# 删除用户信息
cursor.execute('delete from user where id = ?', (4,))
# 执行查询语句
cursor.execute('select * from user')
result4 = cursor.fetchall()  # 使用fetchall方法查询多条数据
print("fetchall result is:", result4)
# 关闭游标
cursor.close()
# 关闭Connection
conn.close()

        执行结果:

fetchone result is: (1, 'zhang')
fetchmany(2) result is: [(2, 'ren'), (3, 'min')]
fetchall result is: [(4, 'xiao'), (5, 'peng'), (6, 'you')]
id >1 result is: [(2, 'ren'), (3, 'min'), (4, 'xiao'), (5, 'peng'), (6, 'you')]
fetchall result is: [(1, 'wang'), (2, 'ren'), (3, 'min'), (5, 'peng'), (6, 'you')]

Process finished with exit code 0

        从执行结果看,增删改查都成功了。

猜你喜欢

转载自blog.csdn.net/qq_33163046/article/details/127679250