Wednesday, March 16, 2011

How can I get the database name from a Perl MySQL DBI handle?

I've connected to a MySQL database using Perl DBI. I would like to find out which database I'm connected to.

I don't think I can use:

$dbh->{Name}

because I call USE new_database and $dbh->{Name} only reports the database that I initially connected to.

Is there any trick or do I need to keep track of the database name?

From stackoverflow
  • You can ask mysql:

    ($dbname) = (each %{$dbh->selectrow_hashref("show tables")}) =~ /^Tables_in_(.*)/;
    

    Update: obviously select DATABASE() is a better way to do it :)

    Harry : Now that's a cool trick.
  • Try just executing the query

    select DATABASE();
    

    From what I could find, the DBH has access to the DSN that you initially connected with, but not after you made the change. (There's probably a better way to switch databases.)

    Harry : Yes the query works: my ($dbname) = $dbh->selectrow_array("select DATABASE()");
  • When you create a connection object it is for a certain database. In DBI's case anyway. I I don't believe doing the SQL USE database_name will affect your connection instance at all. Maybe there is a select_db (My DBI is rusty) function for the connection object or you'll have to create a new connection to the new database for the connection instance to properly report it.

  • FWIW - probably not much - DBD::Informix keeps track of the current database, which can change if you do operations such as CREATE DATABASE. The $dbh->{Name} attribute is specified by the DBI spec as the name used when the handle is established. Consequently, there is an Informix-specific attribute $dbh->{ix_DatabaseName} that provides the actual current database name. See: perldoc DBD::Informix.

    You could consider requesting the maintainer(s) of DBD::MySQL add a similar attribute.

0 comments:

Post a Comment