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.


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?

| improve this question | | | | |

You always have to connect to a database to run CREATE DATABASE. This is the main raison d'être for the postgres database.

There is the createdb executable that does this for you automatically.

| improve this answer | | | | |
  • Is there something similar for creating a new server? – Kerry Nov 18 '19 at 11:11
  • What exactly do you mean by "server"? To create a PostgreSQL cluster, you need to get shell access to the machine (or write an application that does it for you). – Laurenz Albe Nov 18 '19 at 11:20
  • I mean to use the CREATE SERVER call, as defined here postgresql.org/docs/11/sql-createserver.html to create a new server that the script can then connect to and create databases and tables on. – Kerry Nov 18 '19 at 11:24
  • Ah. But that is a foreign server, i.e. a connection to an already existing data source via foreign data wrapper. You cannot create databases via foreign data wrapper. Maybe you should edit the question and say what you are trying to achieve. – Laurenz Albe Nov 18 '19 at 11:33
  • I was trying to achieve a new server, but as it seems that is not possible, my question is answered. Could you please elaborate on the createdb executable? Where is it? Maybe a link to documentation? Thanks! – Kerry Nov 19 '19 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.