Owen wrote:
On Mon, 28 Jun 2010 04:51:45 -0400
"Sharma, Sumit" <sumit.sha...@aeroflex.com> wrote:

I am trying to use Perl to identify if a given database exists or not
and if it doesn't create the database and then connect to it.

Is there any way using Perl DBI to first identify whether a given
database exists or not if it doesn't create the database?

Well I am not sure what you are trying to do, but lets say your
database has the name "my_data.db"

Check that my_data.db exists

   if (-e my_data.db){connect} else {connect and create}

See how you go from there

Creating a database is one of the tasks that varies greatly depending on what DBMS you are using, and the SQL standard also punts and leaves it to the implementations.

If your DBMS is SQLite, then your database is a file and you can use your standard -e file test to see if it exists; if it doesn't, then simply connect() using DBI with the file name as per an existing one, and SQLite defaults to creating said nonexisting database.

If your DBMS is Postgres, what you do depends on whether or not there already exists a database cluster and associated server to connect to. If there is, then you can connect() to it using DBI as the 'postgres' user (or a default user) and then use a SQL command to test the existence of or create a database in the cluster. If there is a cluster but not a server, you could invoke the 'postgres' program to start a server to use that cluster as its data, then procede to the previous sentence. Or if there is no cluster, then you could invoke the 'initdb' program to create one, then start the server, and connect, etc. All of this you can do within Perl of course.

If your DBMS is something else, then I don't know the answer offhand.

-- Darren Duncan

Reply via email to