python代码操作sqlite3数据库方法

python代码操作单文件数据库sqlite3 CRUD方法,请注意insert 插入数据的灵活性操作!

import sqlite3

#生成一个数据库连接对象conn
conn = sqlite3.connect("test.db") # 如果文件不存在,会自动创建
#您可以通过连接对象创建一个游标对象,用于执行 SQL 语句,例如:

cursor = conn.cursor()
cursor.execute("create table if not exists user (id integer primary key, name text, age integer)") # 创建一个 user 表
cursor.execute("insert into user (id, name, age) values (1, 'Alice', 20)")  # 插入一条记录
for i in range(2, 10):  
    cursor.execute("insert into user (name, age) values ('cnliutz', {})".format(60+i))
    # Replace 'Unknown' with the actual name
    data = ('John Doe'+str(i), 25+i)
    cursor.execute("insert into user (name, age) values ( ?, ?)", data)

conn.commit() # 提交事务
 
#您可以使用游标对象的 fetchone(), fetchmany() 或 fetchall() 方法来获取查询结果集中的数据,例如:
 
cursor.execute("select * from user where age > 18") # 查询年龄大于 18 的用户
users = cursor.fetchall() # 获取所有符合条件的用户
for user in users:
    print(user) # 打印每个用户的信息
 
#您可以使用游标对象的 execute() 或 executemany() 方法来更新或删除数据,例如:
 
cursor.execute("update user set age = 21 where id = 1") # 更新 id 为 1 的用户的年龄为 21
cursor.executemany("delete from user where name = ?", [("Alice",), ("Bob",)]) # 删除名字为 Alice 或 Bob 的用户
conn.commit() # 提交事务
 
#最后,您需要关闭游标和连接对象,以释放资源,例如:
 
cursor.close()
conn.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值