I am writing a script in python 3.7, using psycopg2 to set up a new database from scratch. In all the tutorials I have seen, using psycopg2 starts by connecting to a database and getting a cursor object that can then be used to execute psql commands.
Example:
import psycopg2
conn = psycopg2.connect(database="postgres", user="postgres")
cur = conn.cursor()
cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
Is it necessary to connect to a database on one server in order to create a new server using psql (and psycopg2) or can you create a server first and then connect to it?
Best Answer
You always have to connect to a database to run
CREATE DATABASE
. This is the main raison d'être for thepostgres
database.There is the
createdb
executable that does this for you automatically.