使用psycopg2 fail创建表

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

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

  1. # connect to postgres
  2. connection = psycopg2.connect(dbname="postgres", user="osboxes", password="osboxes.org", host="localhost")
  3. connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
  4. cursor = connection.cursor()
  5. # create database to work on
  6. name_database = "image_comparation"
  7. cursor.execute("DROP DATABASE IF EXISTS {0};".format(name_database))
  8. cursor.execute("CREATE DATABASE {0};".format(name_database))
  9. name_table = "IMAGES"
  10. cursor.execute("DROP TABLE IF EXISTS {0};".format(name_table))
  11. # here is the issue, never creates the table
  12. try:
  13. # cursor.execute("DROP TABLE IF EXISTS {0};".format(name_table))
  14. 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)
  15. cursor.execute(create_table_query)
  16. connection.commit()
  17. except psycopg2.DatabaseError as e:
  18. print(f'Error {e}')

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

  1. psql (12.3 (Ubuntu 12.3-1.pgdg18.04+1), server 12.2 (Ubuntu 12.2-4))
  2. Type "help" for help.
  3. image_db=> \dt
  4. Did not find any relations.
  5. image_db=>

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

kognpnkq

kognpnkq1#

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

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

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

相关问题