Python 如果我没有';你没有桌子吗?

Python 如果我没有';你没有桌子吗?,python,pandas,sqlalchemy,Python,Pandas,Sqlalchemy,在将某些数据写入数据框之前,我想删除一个表(如果存在): def store_sqlite(in_data, dbpath = 'my.db', table = 'mytab'): database = sqlalchemy.create_engine('sqlite:///' + dbpath) ## DROP TABLE HERE in_data.to_sql(name = table, con = database, if_exists = 'append') databa

在将某些数据写入数据框之前,我想删除一个表(如果存在):

def store_sqlite(in_data, dbpath = 'my.db', table = 'mytab'):
  database = sqlalchemy.create_engine('sqlite:///' + dbpath)
  ## DROP TABLE HERE
  in_data.to_sql(name = table, con = database, if_exists = 'append')
  database.close()
SQLAlchemy文档都指向一个
Table.drop()
对象-我应该如何创建该对象,或者等效地,是否有其他方法可以删除该表


注意:我不能只使用
如果存在='replace'
,因为输入数据实际上是一个数据帧的dict,我循环了一遍-为了清晰起见,我已经抑制了该代码(我希望如此)

您应该能够从SQLAlchemy引擎创建光标

import sqlalchemy

engine = sqlalchemy.create_engine('sqlite:///' + dbpath)
connection = engine.raw_connection()
cursor = connection.cursor()
command = "DROP TABLE IF EXISTS {};".format(table)
cursor.execute(command)
connection.commit()
cursor.close()

# Now you can chunk upload your data as you wish
in_data.to_sql(name=table, con=engine, if_exists='append')
如果将大量数据加载到数据库中,您可能会发现使用pandas的
to_csv()
和SQL的
copy_from
函数会更快。您还可以使用
StringIO()
将其保存在内存中,并且必须写入文件。

来自panda文档

您也可以运行普通查询,而无需使用execute()创建数据帧。这对于不返回值的查询(如INSERT)非常有用。这在功能上相当于在SQLAlchemy引擎或db连接对象上调用execute

所以我这样做

from pandas.io import sql
sql.execute('DROP TABLE IF EXISTS %s'%table, engine)
sql.execute('VACUUM', engine)
其中“引擎”是SQLAlchemy数据库对象(上面是OP的“数据库”)。真空是可选的,只是减小了sqlite文件的大小(我在代码中很少使用表删除部分)