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?

Answers


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.)


$dbh->{Name} returns the db name from your db handle.

If you connected to another db after connected with your dbh, using mysql query "USE db_name", and you did not setup a new perl DBI db handle, of course, $dbh->{Name} will return the first you previously connected to... It's not spontaneic generation.

So to get the connected db name once the db handle is set up - for DBI mysql:

sub get_dbname {  
    my ($dbh) = @_;  
    my $connected_db = $dbh->{name};  
    $connected_db =~ s/^dbname=([^;].*);host.*$/$1/;  
    return $connected_db;  
}  

You can ask mysql:

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

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


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.


Need Your Help

Cannot open include file with Visual Studio

c++ visual-studio visual-studio-2012 include codeblocks

I have recently gone from Code::Blocks to Visual Studio, and in Code::Blocks one could just add a class and then include it straight away. However, whenever I do the same in Visual Studio with the

need clarification on this code I am writing to find the mode of an array

javascript

For some reason I have just not been able to understand what is going on in this code