python--杂识--18.1--pandas数据插入sqlite并进行查询

python 复制代码
import pandas as pd
import sqlite3

connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
connection.execute("PRAGMA case_sensitive_like = true;")


file_path = "test.csv"
table_name = "student"
filed_name= "name"


header = pd.read_csv(file_path, nrows=1).to_dict(orient="records")[0]

create_table_sql = f"CREATE TABLE {table_name} (" + \
                   ",".join(["{0} {1}".format(key, value) for key, value in header.items()]) + ")"
connection.execute(create_table_sql)

# 查看表结构
cursor.execute("PRAGMA table_info(student)")
print("字段信息:")
for field in cursor.fetchall():
    print(f"名称:{field[1]:<6} | 类型:{field[2]:<8} | 主键:{field[5]}")

# pd读csv内容
df = pd.read_csv(file_path, encoding="utf-8", skiprows=[1], na_values=["null"], keep_default_na=False, dtype=object)
print(df)
# pd将数据插入sqlite
df.to_sql(table_name, connection, if_exists="append", index=False)

# 查表数据
query = f"select name, age, sex, class from {table_name}"
result = pd.read_sql_query(query, connection)
print(result)
connection.close()
相关推荐
蓝博AI4 小时前
2027基于yolov8飞机蒙皮缺陷检测,支持图像,视频和摄像实时检测,python源码
开发语言·python·yolo
是菜鸡小小陈啊4 小时前
【CS329Z Assignment 1】从零构建 LLM Agent Harness(学习笔记)08
笔记·python·学习·大模型·llm
人工智能技术咨询.5 小时前
高质量数据集的一致性
python
IT小小猪6 小时前
子进程闪黑窗:pythonw 没有控制台,0x08000000 一个参数解决
运维·windows·python·自动化·进程管理
2601_962885727 小时前
如何用 Python 计算终极振荡器(Ultimate Oscillator, UOS)?
开发语言·python
Thanks_ks7 小时前
Python 列表与元组:可变性与不可变性的差异及使用场景选择
数据结构·python·列表·元组·可变对象·不可变对象·可哈希
benchmark_cc8 小时前
一次获取多只股票实时行情:QuantDash `quotes.get(symbols=[...])` 批量快照
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
geovindu8 小时前
python: PCA
开发语言·后端·python·算法
AI模型调用笔记9 小时前
流式 API 的 usage 为 null?用 cURL 看尾帧,别漏空 choices
python
天诰10 小时前
SA-T-06 轨迹数据工程 脏数据检测
人工智能·python·算法·语言模型·ai编程