Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

'use database' for sqlserver

by fionbarr (Friar)
on May 21, 2013 at 20:00 UTC ( #1034595=perlquestion: print w/ replies, xml ) Need Help??
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?

Comment on 'use database' for sqlserver
Download Code
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=\\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 (Pope) 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")'


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


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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1034595]
Approved by Old_Gray_Bear
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2016-05-25 22:53 GMT
Find Nodes?
    Voting Booth?