脚本不执行 cur.execute() 中的命令

A script doesn't execute the command in cur.execute()

我是 PostgreSQL 和 psycopg2 的新手,我遇到了一个问题。

import psycopg2


def create_tables(whichone):

     in_str_station = "CREATE TABLE station (id SMALLINT NOT NULL PRIMARY KEY,  name VARCHAR(40) NOT NULL," \
                 " country VARCHAR(3) NOT NULL, latitude VARCHAR(10),  " \
                 "longitude VARCHAR(10),height SMALLINT);"

     in_str_dailyData = "CREATE TABLE daily_data (id BIGSERIAL NOT NULL PRIMARY KEY," \
                   "s_id SMALLINT NOT NULL REFERENCES station(id)," \
                   "d_date DATE NOT NULL, d_mean NUMERIC(6, 1), quality SMALLINT);"

     int_str_monthlyMean = "CREATE TABLE monthly_mean (id BIGSERIAL NOT NULL PRIMARY KEY,"\
                      "s_id SMALLINT NOT NULL REFERENCES station(id),"\
                      "m_date DATE NOT NULL, m_mean NUMERIC(9, 3),"\
                      "var NUMERIC(9, 3), std NUMERIC(9, 3));"

     in_str_yearlymean = "CREATE TABLE yearly_mean (id BIGSERIAL NOT NULL PRIMARY KEY, " \
                    "s_id SMALLINT NOT NULL REFERENCES station(id)," \
                    "y_date DATE NOT NULL, y_mean NUMERIC(9, 3),var NUMERIC(9, 3)," \
                    "std NUMERIC(9, 3), var_m NUMERIC(9, 3), std_m NUMERIC(9, 3));"

     database_list = {'station': in_str_station, 'monthly_mean': int_str_monthlyMean,
                 'daily_data': in_str_dailyData, 'yearly_mean': in_str_yearlymean}

     try:
        conn = psycopg2.connect(
          host="localhost",
          database="climate",
          user="postgres",
          password="1")

       cur = conn.cursor()
       in_str = database_list.get(whichone)
       cur.execute(in_str)
       output_ = cur.fetchall()
       print(output_)
       cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
       print(error)
    finally:
       if conn is not None:
          conn.close()

在我 运行 脚本之后,无论我选择 in_str_ 中的哪一个,都不会创建 table。我已经检查过,当我复制在 cur.execute 中执行的 in_str 的内容并在 PostgreSQL 中使用它时shell,一切正常。

我哪里错了?

我不知道你是不是在这里做的,但缩进错了。您需要在函数后缩进代码。

def foo(a):
    pass

cur.execute() 之后 conn.close() 之前调用 conn.commit()。与 psycopg2 的交易 are not implicitly committed

If the connection is closed (using the close() method) or destroyed (using del or by letting it fall out of scope) while a transaction is in progress, the server will discard the transaction.