【发布时间】: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