gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:12:50 27 4
gpt4 key购买 nike

我有这段代码可以循环查找目录中的 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

最佳答案

这是我的代码:

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

关于python - pandas 添加sql表,检查表是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27939643/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com