首页 > 解决方案 > 通过 Flask-sqlalchemy 在 postgresql db 中创建表时出现语法错误

问题描述

我正在尝试使用flask-sqlalchemy在我在AWS EC2实例中的postgresql db中创建一个新表,如下所示:

def table_create():
    conn = psycopg2.connect(
        dbname='XYZ',
        user='ABC',
        host='ec2-xx-xxx-xxx-xxx.eu-central-1.compute.amazonaws.com',
        password='mypassword')
    cursor = conn.cursor()
    create_table_query = '''CREATE TABLE price_ht
    (ID SERIAL PRIMARY KEY NOT NULL,
    country_code CHAR(2) NOT NULL,
    value float(2) NOT NULL,
    start timestamp with time zone NOT NULL,
    end timestamp with time zone NOT NULL,
    price_type VARCHAR(32) NOT NULL)'''
    cursor.execute(create_table_query)
    cursor.execute("CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;")
    cursor.execute(
        "SELECT create_hypertable('price_ht', 'id', chunk_time_interval=>24)")
    conn.commit()
    print("Table created")

当我运行代码时,我收到以下错误:

发生异常:在“结束”第 6 行或附近出现 SyntaxError 语法错误:时区不为空的结束时间戳,

存储的值必须如下:

在此处输入图像描述

谁能告诉我我在做什么错误?

标签: pythonpostgresqlpsycopg2

解决方案


end是 Postgresql 中的保留字。在命名事物时使用这些通常是“不好的做法”,并且在您的情况下会产生语法错误。

如果您真的想使用它 - 您必须将它包含在".

CREATE TABLE price_ht
    (ID SERIAL PRIMARY KEY NOT NULL,
    country_code CHAR(2) NOT NULL,
    value float(2) NOT NULL,
    start timestamp with time zone NOT NULL,
    "end" timestamp with time zone NOT NULL,
    price_type VARCHAR(32) NOT NULL)

推荐阅读