Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Postgresql CREATE DATABASE IF NOT EXISTS is error

I tried to learn about postgresql using python. I want to create condition CREATE DATABASE IF NOT EXISTS, but I always get an error. The error is :

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

like image 913
Stefani Johnsson Avatar asked Jun 13 '17 03:06

Stefani Johnsson


2 Answers

Postgres does not support the condition IF NOT EXISTS in the CREATE DATABASE clause, however, IF EXISTS is supported on DROP DATABASE

There are two options:

  1. drop & recreate

    cursor.execute('DROP DATABASE IF EXISTS python_db')
    cursor.execute('CREATE DATABASE python_db')
    # rest of the script
    
  2. check the catalog first & branch the logic in 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
    
like image 195
Haleemur Ali Avatar answered Nov 03 '22 06:11

Haleemur Ali


You could query from pg_catalog.pg_database to check if the database is exist like this:

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

Then from here you can add the logic to create your db.

like image 20
Tiny.D Avatar answered Nov 03 '22 05:11

Tiny.D