我已经尝试用Python中的SQLAlchemy创建一个表MYTABLENAME。我通过我的SQL客户机Dbeaver删除所有表,但是我得到一个表存在的错误,这样

Traceback (most recent call last):
  File "/home/hhh/anaconda3/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/home/hhh/anaconda3/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)
psycopg2.ProgrammingError: relation "ix_MYTABLENAME_index" already exists

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) relation "ix_MYTABLENAME_index" already exists
 [SQL: 'CREATE INDEX "ix_MYTABLENAME_index" ON "MYTABLENAME" (index)']

我用一个唯一的名称成功地创建了表及其插入,但是第二次尽管删除了Dbeaver中的表,我还是得到了错误。
小例子
from datetime import date
from sqlalchemy import create_engine
import numpy as np
import pandas as pd

def storePandasDF2PSQL(myDF_):
    #Store results as Pandas Dataframe to PostgreSQL database.
    #
    #Example
    #df=pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
    #dbName= date.today().strftime("%Y%m%d")+"_TABLE"
    #engine = create_engine('postgresql://hhh:yourPassword@localhost:1234/hhh')
    #df.to_sql(dbName, engine)

    df      = myDF_
    dbName  = date.today().strftime("%Y%m%d")+"_TABLE"
    engine  = create_engine('postgresql://hhh:yourPassword@localhost:1234/hhh')
    # ERROR: NameError: name 'table' is not defined
    #table.declarative_base.metadata.drop_all(engine)    #Drop all tables

    #TODO: This step is causing errors because the SQLAlchemy thinks the
    #TODO: table still exists even though deleted
    df.to_sql(dbName, engine)

清理后端(例如一些挂起的索引)以便用新数据重新创建表的正确方法是什么?换句话说,如何解决这个错误?

最佳答案

问题可能来自sqlalchemy,它认为存在索引,因为删除表的消息没有通知sqlalchemy。有一种sqlalchemy方法可以删除表

table.declarative_base.metadata.drop_all(engine)

这应该让Sqlalchemy了解删除的情况。

关于python - Python SQLAlchemy:psycopg2.ProgrammingError关系已存在?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50107615/

10-08 23:31
查看更多