csv文件存储到mysql

import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.types import NVARCHAR, Float, Integer, DateTime
import os
import chardet

#文件路径
file_path = 'D:\csv源\\'
#数据库
db_name = ''
#数据库用户名
db_un = ''
#数据库密码
db_pw = ''


#获取目标文件夹内所有后缀名为.csv的文件
def file_list():
    list = []
    path_list=os.listdir(file_path)
    for filename in path_list:
        if os.path.splitext(filename)[1] == '.csv':
            list.append(filename)
    return list

# 获取文件编码类型
def get_encoding(file):
    # 二进制方式读取,获取字节数据,检测类型
    with open(file, 'rb') as f:
        return chardet.detect(f.read())['encoding']

# pandas类型和sql类型转换
def map_types(df):
    dtypedict = {}
    for i, j in zip(df.columns, df.dtypes):
        if "object" in str(j):
            dtypedict.update({i: NVARCHAR(length=255)})
        if "float" in str(j):
            dtypedict.update({i: Float(precision=2, asdecimal=True)})
        if "int" in str(j):
            dtypedict.update({i: Integer()})
        elif "datetime" in str(j):
            dtypedict.update({i: DateTime()})
    return dtypedict

#写入数据库
def write_to_db(filePath, biaoName):
    encoding = get_encoding(filePath)
    # pandas读取csv文件
    df = pd.read_csv(filePath, encoding=encoding)
    dtypedict = map_types(df)
    # 通过dtype设置类型 为dict格式{“col_name”:type}
    df.to_sql(name=biaoName, con=con, if_exists='replace', index=False, dtype=dtypedict)


try:
    # 连接设置 连接mysql 用户名 密码
    engine = create_engine('mysql+mysqlconnector://' + db_un + ':' + db_pw + '@localhost:3306/' + db_name)
    # 建立连接
    con = engine.connect()
    print('=====数据库连接成功=====')
    #循环写入
    for file in file_list():
        write_to_db(file_path + file, file.split('.')[0])
        print(file_path + file + ': 写入数据库成功!')
except Exception as e:
    print('出错了!')
    print(e)
else:
    # 关闭数据库连接
    con.close()
    print('=====数据库关闭=====')

  

posted @ 2019-08-02 14:12  面向bug编程  阅读(261)  评论(0)    收藏  举报