python Postgresql CREATE DATABASE如果不是EXISTS是错误

时间:2017-06-13 03:38:14

标签: python postgresql

我尝试使用python了解postgresql。我想创建条件CREATE DATABASE如果不是EXISTS,但alayas错误。错误是:

File "learn_postgres.py", line 27, in InitDatabase
cursor.execute("CREATE DATABASE IF NOT EXISTS python_db")

psycopg2.ProgrammingError: syntax error at or near "NOT"
LINE 1: CREATE DATABASE IF NOT EXISTS python_db

2 个答案:

答案 0 :(得分:7)

Postgres不支持CREATE DATABASE子句中的条件IF NOT EXISTS但是IF EXISTS支持DROP DATABASE

有两种选择:

  1. drop&重新创建

    cursor.execute('DROP DATABASE IF EXISTS python_db')
    cursor.execute('CREATE DATABASE python_db')
    # rest of the script
    
  2. 首先查看目录&在python中分支逻辑

    cursor.execute("SELECT 1 FROM pg_catalog.pg_database WHERE datname = 'python_db'")
    exists = cursor.fetchone()
    if not exists:
        cursor.execute('CREATE DATABASE python_db')
    # rest of the script
    

答案 1 :(得分:1)

您可以从pg_catalog.pg_database查询数据库是否存在,如下所示:

SELECT datname FROM pg_catalog.pg_database WHERE datname = 'python_db'

然后从这里你可以添加逻辑来创建你的数据库。