http://www.perlmonks.org?node_id=923648


in reply to How to find MySQL database exist or not

edi:

I'd make the following change:

if (defined $dbh) { print "Table does not exist.\n"; }

The version you have checks whether $dbh is 0. (Had you used eq instead of ==, it would have checked whether $dbh contained the string 'undef'.)

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: How to find MySQL database exist or not
by JavaFan (Canon) on Sep 01, 2011 at 15:57 UTC
    I would not make the same change. Why bother wrapping an "X or die" inside an eval, then check whether X is false afterwards?
    if ($dbh = DBI->do('dbi:mysql: xxxxx','root','')) { print "Table exists\n" } else { print "Table does not exists"; }
    Of course, all it checks is whether one can connect - not whether a database exists (title question) or whether a table exists (message printed).

      JavaFan:

      Good point. I just saw the $blah == 'undef' and was immediately horrified.

      ;^)

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

      And, once we are at nitpicking, it checks it after the program starts, not before (per spec). :)
      thank you JavaFun for the reply. but it is giving an error as follows: Name "main::dbh" used only once: possible typo at C:/Program Files..... Can't locate auto/DBI/do.al in @INC
Re^2: How to find MySQL database exist or not
by edi (Initiate) on Sep 02, 2011 at 11:12 UTC
    use DBI; eval { $dbh = DBI->do('dbi:mysql:xxxxxxx','root','') or die "Connection Error: $DBI::errstr\n" } ; if (defined $dbh) { print "Table does not exist.\n"; } else { print "Table exist";}
    code will print "Table exist" whether the database exist or not. Please help.
      I think that you are mixing up a couple of things.

      There is a dataset name ($dsn) which is a mySQL database on a particular host name and port number. That has to exist or you are going "nowhere"!

      If the $dsn exists, then you can attempt to connect to it. This is where the user name and passwords are required.

      my $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port" || die "DB data set name failed $!\n"; # # second step # # my $dbh = DBI->connect($dsn, $user, $password) || die "DB connect failed $!\n";
      The $dsn and the final connected handle, $dbh are very different things.