如何使用python创建和维护sqlite3数据库

sqlite3是轻量级运行和模拟关系数据库的有效工具。

这里参考网络资料,示例python创建维护sqliite3数据库,演示如何插入、查询、更新和删除数据。

1 创建数据库

使用 connect() 函数创建了一个到名为 case.db 的数据库的连接。

复制代码
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')

2 创建表

在创建数据库后,就可以进一步创建表,示例python代码如下。

创建包含 id、name、age 和 gender 列的表。

id 列是主键,表示一个学生的唯一标识符;

name 列存储学生的姓名;

age 列存储学生的年龄;

gender 列存储学生的性别。

复制代码
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')

# 创建表
conn.execute('''CREATE TABLE students
             (id INT PRIMARY KEY     NOT NULL,
             name           TEXT    NOT NULL,
             age            INT     NOT NULL,
             gender         TEXT    NOT NULL);''')

# 提交更改
conn.commit()

# 关闭连接
conn.close()

3 插入数据

创建完表后,就可以插入数据,示例代码如下。

使用 INSERT INTO 语句将student数据插入到表中。

复制代码
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')

# 插入数据
conn.execute("INSERT INTO students (id, name, age, gender) \
              VALUES (1, 'Tom', 20, 'Male')")

# 提交更改
conn.commit()

# 关闭连接
conn.close()

4 查询数据

在插入数据后,就可以示例数据查询了。

使用execute() 执行 SELECT 语句,使用for循环遍历查询结果。

在每次循环中,打印出每个学生的 ID、姓名、年龄和性别。

复制代码
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')

# 查询数据
cursor = conn.execute("SELECT id, name, age, gender from students")
for row in cursor:
   print("ID = ", row[0])
   print("Name = ", row[1])
   print("Age = ", row[2])
   print("Gender = ", row[3])

# 关闭连接
conn.close()

输出如下

ID = 1

Name = Tom

Age = 20

Gender = Male

5 更新数据

由于数据库中已有数据,这里就可以示例数据更新了。

执行UPDATE语句,将ID为1的学生的年龄更新为 21。

复制代码
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')

# 更新数据
conn.execute("UPDATE students set age = 21 where id = 1")

# 提交更改
conn.commit()

# 关闭连接
conn.close()

6 删除数据

这里是删除数据示例,删除 "students" 表中 ID 为 1 的学生的记录。

复制代码
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')

# 删除数据
conn.execute("DELETE from students where id = 1")

# 提交更改
conn.commit()

# 关闭连接
conn.close()

reference


SQLite 创建一个表在 sqlite3 Python 中

https://geek-docs.com/sqlite/sqlite-questions/253_sqlite_creating_a_table_in_sqlite3_python.html

相关推荐
m0_748554811 天前
golang如何实现用户订阅偏好管理_golang用户订阅偏好管理实现总结
jvm·数据库·python
早日退休!!!1 天前
《数据结构选型指南》笔记
数据结构·数据库·oracle
xcLeigh1 天前
KES数据库性能优化实战
数据库·sql·性能优化·sql优化·数据性能
阿正呀1 天前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
yoyo_zzm1 天前
Laravel9.x新特性全解析
数据库·mysql·nginx
2501_901200531 天前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
m0_495496411 天前
mysql处理复杂SQL性能_InnoDB优化器与MyISAM差异
jvm·数据库·python
forEverPlume1 天前
PHP怎么使用Eloquent Attribute Composition属性组合_Laravel通过组合构建复杂属性【方法】
jvm·数据库·python
2301_809204701 天前
mysql在docker容器中如何部署_利用docker-compose快速启动
jvm·数据库·python
虹科网络安全1 天前
艾体宝产品|深度解读 Redis 8.4 新增功能:原子化 Slot 迁移(上)
数据库·redis·bootstrap