【问题标题】:Connect to SQL Server 2005 from Perl and do a SELECT从 Perl 连接到 SQL Server 2005 并执行 SELECT
【发布时间】:2009-05-22 09:03:10
【问题描述】:

如何通过 Perl 脚本在 SQL Server 2005 上执行 SELECT?

【问题讨论】:

    标签: sql-server-2005 perl


    【解决方案1】:

    您将需要使用 DBI,并且您最好使用来自 (CPAN) 的 DBD::ODBC 提供程序。如果您不了解 DBI,那么您需要阅读相关内容。有一本书 (Programming the Perl DBI) 很旧但仍然有效。

    然后是以下内容:

    use strict;
    use warnings;
    use DBI;
    
    # Insert your DSN's name here.
    my $dsn = 'DSN NAME HERE'
    
    # Change username and password to something more meaningful
    my $dbh = DBI->connect("DBI:ODBC:$dsn", 'username', 'password')
    
    # Prepare your sql statement (perldoc DBI for much more info).
    my $sth = $dbh->prepare('select id, name from mytable');
    
    # Execute the statement.
    if ($sth->execute)
    {
        # This will keep returning until you run out of rows.
        while (my $row = $sth->fetchrow_hashref)
        {
            print "ID = $row->{id}, Name = $row->{name}\n";
        }
    }
    
    # Done. Close the connection.
    $dbh->disconnect;
    

    【讨论】:

    • 如果您在 Unix-ish 平台上,DBD::ODBC 可能会很痛苦,最好将 DBD::Sybase 与 FreeTDS 一起使用。 (好吧,我上次尝试 UnixODBC 时非常痛苦)
    • @araqnid - 我打算提到 FreeTDS,但决定避免使这件事复杂化。我自己也享受过 UnixODBC 的乐趣 :)
    【解决方案2】:

    这是一个使用 DBI 的基本示例(在评论后编辑):

    use DBI;
    
    my $dbh = DBI->connect("dbi:Sybase:database=<dbname>;server=<servername>",
        <user>, <password>, 
        { PrintError => 0, RaiseError => 1 });
    my $sth = $dbh->prepare( "select field from table" );
    my $result = $sth->execute();
    while( my $result = $sth->fetchrow_hashref ) {
        print $result->{field};
    }
    $sth->finish;
    $dbh->disconnect;
    

    希望通过更简单的解决方案看到其他答案:)

    【讨论】:

    • 一般不需要指定dbi_connect_method。而且我建议使用“PrintError => 0, RaiseError => 1”,以便引发 SQL 错误......尤其是因为您不进行任何错误检查;)您甚至可以通过说“for my $row in (@{ $dbh->selectall_arrayref("select field from table", { Slice => {} })}) { print "$row->{field}\n"; } 如果你要使用 fetchrow_hashref或者它的朋友,在连接到数据库时也值得设置“FetchHashKeyName => 'NAME_lc'”,有些人坚持使用 CamelCase 作为列名。但除此之外,很好:)
    【解决方案3】:
            #
            # ------------------------------------------------------
            # run a passed sql and retun a hash ref of hash refs
            # ------------------------------------------------------
            sub doRunSqlGetHashRef {
    
                my $self                   = shift ;
                my $sql                    = shift ;
    
                my $hsr_meta               = {} ;
                my $hsr                    = {} ;
                my $rowid = 0 ;
                my $flag_filled_hsr_meta   = 0 ;
                my $hsr_meta_colid         = 0 ;
    
                use DBI;
    
                my $dbs = "dbi:ODBC:DRIVER=FreeTDS;DSN=DEV_MSSQLSRV_DSN";
                # verify by :
                # isql -v DEV_MSSQLSRV_DSN user pwd
    
                my $dbh = DBI->connect($dbs, $db_user, $db_user_pw)
                    or die "CONNECT ERROR! :: $DBI::err $DBI::errstr $DBI::state $!\n";
    
                if (defined($dbh)) {
    
                    # Prepare your sql statement (perldoc DBI for much more info).
                    my $sth = $dbh->prepare( $sql ) ;
    
                    # Execute the statement.
                    if ($sth->execute) {
                    # This will keep returning until you run out of rows.
                        while (my $row = $sth->fetchrow_hashref)  {
    
                            # fill in the meta hash reference with the col names
                            if ( $flag_filled_hsr_meta == 0 ) {
                                for (@{$sth->{ 'NAME' }}) {
                                    # debug ok print "$_ => $row->{$_}\t";
                                    $hsr_meta->{ $hsr_meta_colid } = $_ ;
                                    $hsr_meta_colid++ ;
                                    $flag_filled_hsr_meta = 1 ;
                                }
                            }
                            # p ( $row ) ; # row level debug ...
                            $hsr->{ $rowid } = $row ;
                            $rowid++ ;
                        }
                    }
                    # Done. Close the connection.
                    $dbh->disconnect;
    
                    # debug ok p( $hsr_meta ) ;
    
                    return ( $hsr_meta , $hsr )  ;
                }
                else {
                    print "Error connecting to database: Error $DBI::err - $DBI::errstr\n";
                }
    
            }
            #eof sub doRunSqlGetHashRef
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多