fionbarr has asked for the wisdom of the Perl Monks concerning the following question:

I have been connecting to MSSQLSERVER with the following code:
my $dbs = "dbi:ODBC:DRIVER={SQL Server};SERVER={$server}"; $dbh = DBI->connect( $dbs, $username, $password, { PrintError => 1 } +);
There was only one database; now I have two and I need to select which one I want. What's the syntax for this please?

Replies are listed 'Best First'.
Re: 'use database' for sqlserver
by mje (Curate) on May 22, 2013 at 08:50 UTC

    The following works fine for me:

    $ perl -le 'use DBI; my $h = DBI->connect("dbi:ODBC:DRIVER={Easysoft O +DBC-SQL Server};server=172.20.0.39\\SQLEXPRESS;UID=xxx;PWD=yyy;databa +se=master;")'

    and if I put an unknown database in it fails to login.

      This one works:
      my $connect_string = "dbi:ODBC:DRIVER={SQL Server};SERVER={$server};UI +D=$username;PWD=$password;DATABASE=$db;"; $dbh = DBI->connect($connect_string);
      Thanks to all.
Re: 'use database' for sqlserver
by Corion (Patriarch) on May 21, 2013 at 20:02 UTC

    You put the one you want into $server and that's it.

    Whoops - "database", not "server".

      didn't work at all. Is there something on the order of 'dbh->do("use $database")'

        fionbarr:

        I'd be surprised if $dbh->do("use $database") didn't work. Did you try it and have it fail?

        ...roboticus

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

Re: 'use database' for sqlserver (connectionstrings)
by Anonymous Monk on May 21, 2013 at 22:52 UTC
    Try http://www.ConnectionStrings.com/ says Database=myDataBase; so you might try Database={$database}; or even  $dbh->do("use ". $dbh->quote_identifier($database) );
      I use $dbh->do("use $database"); ('$database' is sufficiently trusted in my env, YMMV). Putting the database into the connect string, at least for DBD::Sybase (I don't know about DBD::ODBC), resulted in a warning when I really wanted it to throw an error, e.g., when the server was up, but the database was not 'ready'. The do(..) method throws an error if RaiseError is set.