Postgres psycopg2:关闭连接后,关系/表未保存

时间:2019-12-03 07:17:06

标签: postgresql psycopg2

我正在尝试创建一个表,用于在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)

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

1 个答案:

答案 0 :(得分:0)

您必须致电conn.commit()