pandas添加sql表,检查表是否存在

时间:2015-01-14 09:32:04

标签: python excel sqlite pandas sqlalchemy

我有这段代码在目录中循环excel文件,在sqlite db中添加文件。 如果表存在,我设法通过引发的异常,但我发现这个不优雅且效率低,因为循环读取excel文件,将其添加到Dataframe等等...... 理想情况下,我想在从excel创建df之前测试表的存在。

response = {}
for f in glob('T:\GESTION\toto\titi\tata\file_201*.xlsx'):
    print f
    datereg = re.search('T:\\\\GESTION\\\\toto\\\\titi\\\\tata\\\\file_(\d{4})(\d{2})(\d{2}).xlsx', f)
    if datereg is not None:
        dated = datetime.datetime(int(datereg.group(1)), int(datereg.group(2)), int(datereg.group(3)))
    print dated

    # ideally test if table in db exists here

    xl = pd.ExcelFile(f)
    df = xl.parse(sheetname="Sheet1")
    df = df[extractFields].drop_duplicates(subset='ISIN')
    df = df.set_index('ISIN', verify_integrity=True)
    response[dated] = df
    # print response
    engine = sqlalchemy.create_engine('sqlite:///my_db.sqlite')
    try:
        df.to_sql(dated.__str__(), engine, if_exists='fail')
    except ValueError as err:
        print(err)
        pass

2 个答案:

答案 0 :(得分:2)

从 sqlalchemy 1.4 开始,现在从 has_table 对象调用 Inspector

查看documentation

from sqlalchemy import inspect, create_engine

engine = create_engine('...')
insp = inspect(engine)
table_exist = insp.has_table(table_name, schema)

if table_exist:
    df.to_sql(name, engine)

答案 1 :(得分:1)

这就是我的一些代码:

engine = create_engine("mysql+mysqlconnector://{user}:{pw}@localhost/{db}".format(user="root",pw="password",db="worker"))
check=engine.has_table(worker_name)
            print(check) #boolean
            if check == False:
                df.to_sql(con=engine, name=table_name, if_exists='replace',index=False)