繁体   English   中英

使用 psycopg2 创建表失败

[英]create a table with psycopg2 fail

我正在使用 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 中并且工作正常。 我错过了什么?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM