使用psycopg2 fail创建表

rlcwz9us  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(366)

我正在用python编写一个脚本,每次它运行时都会重新开始,因为我想确保删除数据库和表并重新创建它们。我遵循这个教程:https://www.fullstackpython.com/blog/postgresql-python-3-psycopg2-ubuntu-1604.html 但是matt作为一个用户做了osboxes,但是当我尝试创建表时,我得到了已经存在的错误,如果我以前删除了数据库,那怎么可能呢?


# connect to postgres

connection = psycopg2.connect(dbname="postgres", user="osboxes", password="osboxes.org", host="localhost")
connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cursor = connection.cursor()

# create database to work on

name_database = "image_comparation"
cursor.execute("DROP DATABASE IF EXISTS {0};".format(name_database))
cursor.execute("CREATE DATABASE {0};".format(name_database))

name_table = "IMAGES"    
cursor.execute("DROP TABLE IF EXISTS {0};".format(name_table))

# here is the issue,  never creates the table

try:
    # cursor.execute("DROP TABLE IF EXISTS {0};".format(name_table))
    create_table_query = """CREATE TABLE {0} (IMAGE_PATH TEXT NOT NULL, IN_PROGRESS BOOLEAN, COMPLETED BOOLEAN, TIME_PROCESS REAL, CREATED_TIME timestamp, MATCHES TEXT NULL, MOVED BOOLEAN);""".format(name_table)
    cursor.execute(create_table_query)
    connection.commit()
except psycopg2.DatabaseError as e:
    print(f'Error {e}')

错误关系“images”已存在
我第一次运行脚本的时候,告诉我这个关系allready存在,所以我评估了这个表是如何持久的,所以我签入了cmd

psql (12.3 (Ubuntu 12.3-1.pgdg18.04+1), server 12.2 (Ubuntu 12.2-4))
Type "help" for help.

image_db=> \dt
Did not find any relations.
image_db=>

然后,我手动将create table查询复制到psql中,工作正常。我错过了什么?

kognpnkq

kognpnkq1#

您正在登录到默认数据库“postgres”,将其视为包含postgres中发生的所有其他事情的信息的主数据库,然后创建一个新数据库,但您需要创建另一个到该数据库的连接才能切换到它,现在您正在“主”数据库中创建一个表,添加

connection = psycopg2.connect(dbname="image_comparation", user="osboxes", password="osboxes.org", host="localhost")

切换到那个数据库然后创建故事。

相关问题