【问题标题】:Postgres psycopg2: Relation/Table not saved after closing connectionPostgres psycopg2:关闭连接后未保存关系/表
【发布时间】:2020-03-27 20:00:15
【问题描述】:

我正在尝试创建一个在 postgresql 中记录我的应用程序的表。下面效果很好。

conn = psycopg2.connect(database="db1", user = "postgres", password = "", host = "myhost", port = "5432")
cur = conn.cursor()
cur.execute('''CREATE TABLE login
      (USERNAME VARCHAR(20) NOT NULL,
      TS TIMESTAMP);''')
cur.execute("""INSERT INTO public.login (USERNAME,TS) \
      VALUES ('TEST','2019-12-03')""");
my_table    = pd.read_sql('SELECT * FROM public.login', conn)
conn.close()

我认为表/关系会被创建并保存。但是当我重新连接时,我收到UndefinedTable: relation "public.login" does not exist 的错误。

conn = psycopg2.connect(database="db1", user = "postgres", password = "", host = "myhost", port = "5432")
print ("Opened database successfully")
cur = conn.cursor()
cur.execute("""INSERT INTO public.login (USERNAME,TS) \
      VALUES ('TEST','2019-12-03')""");
my_table    = pd.read_sql('SELECT * FROM public.login', conn)

下面的表格不存在,正如How do I get tables in postgres using psycopg2?中所回答的那样

cur.execute("""SELECT table_name FROM information_schema.tables
       WHERE table_schema = 'public'""")
for table in cur.fetchall():
    print(table)

我很困惑为什么关闭连接会导致这种情况。

【问题讨论】:

  • conn.close()之前尝试conn.commit()

标签: postgresql psycopg2


【解决方案1】:

您必须致电conn.commit()..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 2012-03-14
    • 1970-01-01
    • 2019-10-10
    相关资源
    最近更新 更多