hoow to connect to sql server from a script shell

Discussion in 'Programming/Scripts' started by pattchen, May 2, 2007.

  1. pattchen

    pattchen New Member

    hi,
    I want to write a script shell which must connect to a sql server 2000 database. How may i achieve this?

    thanks.
     
  2. abogothy

    abogothy New Member

    from which platform ?
    You can use freetds generally from *nix...
     
  3. pattchen

    pattchen New Member

    i'm working with red hat linux 9.Thanks for your suggestion about freetds.I checked it on its web site,but there is not indication on HOW i can use it in a script shell.In fact, i'm a newbie in shell scripting,and so,i prefer an example(source code);) .
    May you help me for this issue?

    thanks.
     
  4. abogothy

    abogothy New Member

    Of course :)
    First of all...check your SQL server security configuration. If only integrated security enabled (native windows authentication mode), you cannot connect to your database from linux.
    MSSQL derived from Sybase, so MSSQL is compatible with Sybase tabbed stream protocol. You can use TDS to access mssql database.
    Then download, extract and compile freetds:

    wget ftp://ftp.ibiblio.org/pub/Linux/ALPHA/freetds/stable/freetds-stable.tgz
    tar xvfz freetds-stable.tgz
    cd freetds-0.64
    ./configure
    make
    make install

    If you want to run queries on MSSQL from linux, I propose you to use a simple perl script which connects to database, authenticates you on MSSQL server, runs a query then get back results to you,,,so you need a perl (included in your distro) and a sybase module...for example DBD::Sybase.
    Start cpan and install DBD::Sybase module. Set SYBASE env variable to directory you've set previously (by default /usr/local used in freetds), then start DBD::Sybase installation from cpan.org:

    export SYBASE=/usr/local/
    cpan -i DBD::Sybase

    cpan will download sources, and compile perl module, then it will run some tests with you settings (server name, user, password, and database)...
    If you don't want to test on your compile machine, you can use "force install" with cpan...

    So your machine contains freetds library and a perl module that uses it. A script examle that uses MSSQL from linux:

    <- CUT HERE ->
    #!/usr/bin/perl
    #
    use DBI;

    my $dbh = DBI->connect("dbi:ODBC:JDBC", 'guest', 'sybase', {PrintError => 0});

    die "Unable for connect to server $DBI::errstr"
    unless $dbh;

    my $rc;
    my $sth;

    $sth = $dbh->prepare("select \@\@servername");
    if($sth->execute) {
    while(@dat = $sth->fetchrow) {
    print "@dat\n";
    }
    }

    <- CUT HERE ->

    Details described here: http://www.freetds.org/userguide/perl.htm#DBD.SYBASE
     
  5. pattchen

    pattchen New Member

    thanks for all,
    i will try this today and post feedback later.
    hope it will work:) .
     

Share This Page