【问题标题】:UndefinedTable: relation does not existUndefinedTable:关系不存在
【发布时间】:2020-02-26 11:31:54
【问题描述】:

我正在使用python 3.5.2 运行并尝试使用postgres 运行基本命令。

我正在连接到 postgres docker 服务器:

conn = psycopg2.connect(user='postgres', password='docker', host='127.0.0.1', port='5432') 
cursor = self.conn.cursor()

第一次 时间我正在创建一个新表:

sql = '''CREATE TABLE ''' + self.table_name + '''(
         FIRST_NAME CHAR(20) NOT NULL,
         LAST_NAME CHAR(20),
         AGE INT,
         SEX CHAR(6),
         INCOME FLOAT
      )'''
cursor.execute(sql)

并插入行:

def add_emloyee(name, last, age, sex, income):
    sql = '''INSERT INTO ''' + self.table_name + '''(FIRST_NAME,LAST_NAME, AGE,SEX,INCOME)
        VALUES (%s, %s, %s, %s, %s)'''
    cursor.execute(sql, (name, last, age, sex, income))

一切正常。 但是当我再次运行应用程序时(在我关闭它并再次运行之后)并注释创建表命令(因为我在之前的运行中创建了它),并尝试将新数据插入表中,我收到错误:

psycopg2.errors.UndefinedTable: relation "employee" does not exist
LINE 1: INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE,SEX,INCOME)

为什么会这样?

【问题讨论】:

  • 您记得提交更改到数据库吗?

标签: python postgresql


【解决方案1】:

我在创建表(或添加新行)后错过了commit 命令

conn.commit()

【讨论】:

    【解决方案2】:

    就我而言,我使用的是flask_sqlalchemypostgres

    我忘记在烧瓶外壳中提供create_all,这给了我同样的错误。

    db.create_all()
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2015-07-29
      • 2020-08-08
      • 1970-01-01
      • 2020-05-08
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多