python导出数据到sqlite中

复制代码
import sqlite3

# 数据
data = [
    {'username': '张三', 'age': 33, 'score': 13},
    {'username': '李四', 'age': 44, 'score': 14},
    {'username': '王五', 'age': 55, 'score': 15},
]

# 连接SQLite数据库(如果不存在则创建)
conn = sqlite3.connect('test.db')

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

# 创建users表,id为主键且自动增长
cursor.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        age INTEGER,
        score INTEGER
    );
""")

# 将数据插入到users表中
for user_dict in data:
    cursor.execute("""
        INSERT INTO users (username, age, score)
        VALUES (?, ?, ?)
    """, (user_dict['username'], user_dict['age'], user_dict['score']))

# 提交事务
conn.commit()

# 关闭游标和连接
cursor.close()
conn.close()
相关推荐
小小测试开发6 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想6 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波7 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf7 小时前
Python 异常处理
前端·后端·python
麻雀飞吧8 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy8 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.8 小时前
【01】Python 机器学习
开发语言·python
为爱停留8 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t9 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦9 小时前
Python 搭建简易HTTP服务
开发语言·python·http