How do I connect with Perl to SQL Server?

前端 未结 2 1235
南旧
南旧 2021-02-01 09:49

I have a user id, password, database name and datasource details. I want to connect with Perl to a MSSQL server. I just used the following snippet, but I am getting an error.

相关标签:
2条回答
  • 2021-02-01 10:32

    Everything following 'dbi:ODBC:' in your connection string is passed to the ODBC driver. For MSSQL, try this connection string:

    DBI->connect("dbi:ODBC:Driver={SQL Server};Server=192.168.3.137;UID=$user;PWD=$password")
    

    You can find some more alternatives on connectionstrings.com

    0 讨论(0)
  • 2021-02-01 10:39

    I am on Ubuntu (20.04) and followed the instructions to install SLQ Server in a docker container: https://docs.microsoft.com/en-us/sql/linux/quickstart-install-connect-docker?view=sql-server-ver15&pivots=cs1-bash

    I created the TestDB and the table Inventory as per the tutorial.

    I installed the ODBC driver following https://docs.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15

    The driver library file was /opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1

    With that, the following script successfully connects to the DB and returns the content of the table:

     #!/usr/bin/perl
    use strict;
    use warnings;
    
    use DBI;
    my $user = 'SA';
    my $password = '<YourNewStrong@Passw0rd>';
    
    my $dbh = DBI->connect("dbi:ODBC:Driver={/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1};Server=localhost;Database=TestDB;UID=$user;PWD=$password");
    
    my $sth = $dbh->prepare("SELECT * FROM Inventory");
    $sth->execute();
    
    while ( my @row = $sth->fetchrow_array ) {
          print "@row\n";
    }
    
    0 讨论(0)
提交回复
热议问题