【问题标题】:creating mysql Tables automatically from excel files in folder using python使用python从文件夹中的excel文件自动创建mysql表
【发布时间】:2019-11-10 03:09:18
【问题描述】:

假设这是我的文件夹

enter image description here

从上面的文件夹中,我应该能够通过读取 excel 文件在 mysql 中创建所有表,例如 CricketWorldCup、网球锦标赛等。因此,我可以做些什么来创建所有表,而不是多次创建表表名语句mysql 从 python 中的 excel 文件中提取,因此只需在文件夹中添加一个新的 excel 文件,我就可以在 mysql 中轻松创建表。 请帮我解决这个问题,因为我已经坚持了很长时间。请任何人都可以发布读取excel文件的代码并使用python在mysql中自动创建表(excel表和MySql中的列名应该是一样)

【问题讨论】:

    标签: python mysql csv


    【解决方案1】:

    让我们把问题分解成更小的问题

    1. 读取 Excel 文件
    2. 连接数据库
    3. 插入数据库

    并使用这些代码行解决那些问题。提醒您需要先安装库。假设您使用pip

    您可能不需要pandassqlalchemy,但使用它们会使这个过程更容易。

    pip install pandas sqlalchemy pymysql

    import pandas as pd
    import os
    import sqlalchemy
    
    # connect db
    engine = sqlalchemy.create_engine('mysql+pymysql://user:passwd@localhost:3306/db_name')
    engine.connect()
    
    # reading and insert one file at a time
    for file in os.listdir('.'):
        # only process excels files
        file_basename, extension = file.split('.')
        if extension == 'xlsx':
            df = pd.read_excel(os.path.abspath(file))
            df.to_sql(file_basename, con=engine, if_exists='replace')
    

    【讨论】:

    • 文件 "c:/Users/srich/Desktop/Match The following/tester_file.py", line 16, in df = pd.read_excel(file) File "C:\Program Files \Python37\lib\site-packages\pandas\util_decorators.py”,第 188 行,在包装器中返回 func(*args, **kwargs) 文件“C:\Program Files\Python37\lib\site-packages\pandas\util_decorators .py”,第 188 行,在包装返回 func(*args, **kwargs) 文件“C:\Program Files\Python37\lib\site-packages\pandas\io\excel.py”,第 350 行,在 read_excel io 中= ExcelFile(io, engine=engine) .vs 的权限错误。这些是我得到的错误
    • 在没有提供完整路径的 Windows 上是个问题。我在pd.read_excel(os.path.abspath(file)) 更新了代码
    • 没问题。如果您的问题得到解决,请将答案标记为正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    相关资源
    最近更新 更多