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
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.)
2 Comments
Daniel Vérité
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.