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()
相关推荐
xchenhao20 小时前
SciKit-Learn 全面分析分类任务 breast_cancer 数据集
python·机器学习·分类·数据集·scikit-learn·svm
独行soc1 天前
2025年渗透测试面试题总结-66(题目+回答)
java·网络·python·安全·web安全·adb·渗透测试
Y学院1 天前
Python 数据分析:从新手到高手的“摸鱼”指南
python·数据分析
深耕AI1 天前
【PyTorch训练】准确率计算(代码片段拆解)
人工智能·pytorch·python
eqwaak01 天前
科技信息差(9.12)
开发语言·python·科技·量子计算
Blossom.1181 天前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle
蒋星熠1 天前
破壁者指南:内网穿透技术的深度解构与实战方法
网络·数据库·redis·python·websocket·网络协议·udp
shizidushu1 天前
使用 Pyinstaller 打包 PPOCRLabel
python·pyinstaller
Q_Q19632884751 天前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php