PostgreSQL 关系不存在 (Python)

PostgreSQL relation doesn't exist (Python)

我在 psql 中创建了一个数据库,并在其中创建了一个名为 "tweet" 的 table。

CREATE TABLE tweet 
 ( tid CHARACTER VARYING NOT NULL, DATA json, 
   CONSTRAINT tid_pkey PRIMARY KEY (tid) );

然后当我使用

SELECT * FROM tweet; 

在 psql window 中它工作并显示一个空的 table。

现在我有一个 python 脚本,它获取 JSON 数据并将其加载到这个 table 中。

conn_string = "host='localhost' port=5432 dbname='tweetsql' user='tweetsql' password='tweetsql'"

conn = psycopg2.connect(conn_string)
cur = conn.cursor()

这建立了连接,我认为它没有任何问题。 现在我有一些逻辑可以读取 JSON 文件然后添加它,我说:

cur.execute("INSERT INTO tweet (tid, data) VALUES (%s, %s)", (cur_tweet['id'], json.dumps(cur_tweet, cls=DecimalEncoder), ))

但这总是说关系推文不存在。我在这里错过了什么吗?是我的连接有问题还是我的脚本无法看到 table?作为参考,我使用 psycopg2 进行连接。

编辑:我更新了 DDL 以包含一个我可以提交的事务,但也没有修复它。这是架构问题吗?

这是我对要提交的 table 创建所做的:

BEGIN;
CREATE TABLE tweet 
 ( tid CHARACTER VARYING NOT NULL, DATA json, 
   CONSTRAINT tid_pkey PRIMARY KEY (tid) );
COMMIT;

编辑 2:我在这里发布了一些代码...

import psycopg2
import json 
import decimal 
import os 
import ctypes 

conn_string = "host='localhost' port=5432 dbname='tweetsql' user='tweetsql' password='tweetsql'"
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
cur.execute("CREATE TABLE tweet (tid CHARACTER VARYING NOT NULL, DATA json, CONSTRAINT tid_pkey PRIMARY KEY (tid) );")
cur.commit() 


for file in os.listdir(path):    
    if not is_hidden(file):     
        with open(path+file, encoding='utf-8') as json_file:
            tweets = json.load(json_file, parse_float=decimal.Decimal)
            for cur_tweet in tweets:
                cur.execute("INSERT INTO tweet (tid, data) VALUES (%s, %s)", (cur_tweet['id'], json.dumps(cur_tweet, cls=DecimalEncoder), ))

cur.commit()
cur.close()
conn.close()

您可能没有提交 table 创建,并且(我假设;没有看到您的完整代码)您每次都通过 psycopg2 启动新连接。您需要在 table 创建后立即提交,并且 而不是 在新连接中,因为每个连接都是其自己的隐式事务。所以,你的代码流应该是这样的:

  1. 连接到数据库
  2. 使用光标
  3. 创建 table
  4. 填写table
  5. 提交数据库并断开连接。

或者,如果您必须将创建与填充分开,只需在 (2) 之后提交并断开连接,然后在 (3) 之前重新连接。