【问题标题】:create a table with psycopg2 fail使用 psycopg2 创建表失败
【发布时间】:2020-10-29 14:49:54
【问题描述】:

我正在用 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}')

错误关系“图像”已经存在

我第一次运行脚本之后告诉我关系已经存在所以我假设该表是如何持久化的,所以我检查了 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=> 

然后我手动将创建表查询复制到 psql 中并且工作正常。我错过了什么?

【问题讨论】:

  • 我试过后工作正常,没有任何问题!
  • 也许我正在使用的 vm 中有什么东西?我会尝试在操作和检查之间延迟。
  • 很奇怪,如果我执行另一个脚本并且我只是直接连接到该新数据库并创建表,确实有效,但在原始脚本中没有 =(.. 需要进行更多调查。

标签: python sql postgresql psycopg2


【解决方案1】:

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

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

切换到该数据库,然后创建故事。

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2020-04-12
    • 2016-12-26
    • 2016-03-22
    • 1970-01-01
    • 2012-04-29
    相关资源
    最近更新 更多