繁体   English   中英

Python SQLAlchemy:psycopg2.ProgrammingError关系已存在?

[英]Python SQLAlchemy: psycopg2.ProgrammingError relation already exists?

我已经重复尝试用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知道有关删除的信息。

该答案没有解决相同表名的重用问题,因此与清理SQLAlchemy元数据无关。

不要重用表名,而是将执行时间添加到tableName的末尾

import time 
dbName  = date.today().strftime("%Y%m%d")+"_TABLE_"+str(time.time())
dbTableName = dbName

因此,您的SQL developermnet环境(例如SQL客户端锁定连接或特定表)没有太大关系。 使用SQLAlchemy运行Python时,关闭Dbeaver会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM