4

How can I create a Postgres database from Perl? This is not documented in the Perl Postgres DBI driver DBD::Pg (or pretty much anywhere else). I need to be able to create a scratch database from my program, rather than having to use psql or pgAdmin to create the database.

1 Answer 1

5

The trick is using the 'postgres' database that you will likely have with your installation of Postgres (if you don't have a 'postgres' database, you probably know why). If you connect as user 'postgres' to the 'postgres' database, you can then issue then create database SQL command, like so:

my $dbh = DBI->connect("dbi:Pg:dbname=postgres", "postgres");
$dbh->do('create database "Scratch-School"');

(You might also look at create a postgreSQL database programmatically, which covers this issue at a higher level.)

Sign up to request clarification or add additional context in comments.

2 Comments

You should stay away from quoted identifiers like "Scratch-School". Many tools have problems with that. Better use create database scratch_school making the name case-insensitive and doesn't require you to write those double quotes every time.
The point is that to create a database, you need to be connected first to another existing database. It doesn't have to be postgres, and it's not specific to Perl. It's true even with psql, and even for createdb itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.