from sqlalchemy import *
import pandas as pd
def read_data(file):
"""读取csv文件中的数据,返回Dataframe类型"""
return pd.read_csv(file)
def write_sql(score_pd, table_name):
"""将Dataframe类型数据写入到数据库里的score表中"""
score_pd.to_sql(table_name, con=engine, index=False, if_exists='replace')
def read_sql_to_list(table_name):
"""从数据库中读取数据并转为二维列表类型"""
from_sql = pd.read_sql(table_name, engine) # 从score表读数据
print(from_sql) # 查看dataframe数据
title = from_sql.columns.tolist() # 列表
score = from_sql.values.tolist() # dataframe转二维列表
return [title]+score # 列表拼接
if __name__ == '__main__':
file = 'sqlite:///./scores.db'
table = 'score'
engine = create_engine(file, echo=True)
pd_score = read_data('scoregroup.csv')
write_sql(pd_score, table)
print(read_sql_to_list(table))