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()
相关推荐
炸薯条!14 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
tryCbest14 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
VIP_CQCRE14 小时前
GPT Image 2.6 动态表情交付别只发预览:GIF 文件校验、哈希清单与下载排错
图像处理·人工智能·python·gif
2601_9679873715 小时前
使用 NumPy 和 Python 实现梯度下降
python·机器学习·线性回归·numpy·梯度下降
BD_Marathon15 小时前
Jupyter魔法命令
ide·python·jupyter
词却15 小时前
Python 正则表达式实战:使用 re 模块提取符合条件的字符串
python·正则表达式
汤姆宝库16 小时前
视觉语言模型的实现:LLaVA式投影与指令微调
python·深度学习·语言模型
2601_967979121 天前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
隔窗听雨眠1 天前
Oracle19c集群补丁实战手册
oracle·数据库补丁·opatchauto
AI创界者1 天前
Python 进阶实战(五十八章):配置热更新、优雅停机排空与高并发压测方案
人工智能·python·aigc