AWS Lambda function to connect to SQL Server with Python

前端 未结 1 388
深忆病人
深忆病人 2020-12-10 20:58

I\'ve been stuck trying to connect to an SQL Server using AWS Lambda functions for a long while now.

To do so i\'m trying to use any library (tried with pyodbc, pyp

1条回答
  •  北海茫月
    2020-12-10 21:32

    • you need to know Lambda copy your function in local /var/task/
    • create a instance using Lambda official AMI https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
    • start instance, login
    • yum install gcc gcc-c++
    • go in to /home/ec2-user
    • Download the last unixodbc manager from: ftp://ftp.unixodbc.org/pub/unixODBC/
    • wget ftp://ftp.unixodbc.org/pub/unixODBC/unixODBC-2.3.5.tar.gz
    • tar xvzf unixODBC-2.3.5.tar.gz
    • cd unixODBC-2.3.5
    • configure it with the correct sysconfdir value

      ./configure --sysconfdir=/var/task --disable-gui --disable-drivers --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE --prefix=/home

    • make install
    • Go to /home dir and copy bin,include,lib,share directory on your computer where the Lambda project is (ex: C:\AWS\Lambda\sql_query)
    • install on your EC2 instance the the Microsoft driver libmsodbcsql-13.1.so.9.1 and then copy the driver file on your PC local directory (ex: C:\AWS\Lambda\sql_query\msodbcsql\msodbcsql\lib64 )
    • Take a look https://blogs.msdn.microsoft.com/sqlnativeclient/2017/02/04/odbc-driver-13-1-for-linux-released/
    • On your computer, in the same root directory create file odbcinst.ini

    [ODBC Driver 13 for SQL Server] Description=Microsoft ODBC Driver 13 for SQL Server Driver=/var/task/msodbcsql/msodbcsql/lib64/libmsodbcsql-13.1.so.9.1 UsageCount=1

    • On your computer, in the same root directory create file odbc.ini

      [ODBC Driver 13 for SQL Server] Driver = ODBC Driver 13 for SQL Server Description = My ODBC Driver 13 for SQL Server Trace = No

    • on your python program use pyodbc:

      import pyodbc def lambda_handler(event, context): server = "xxxxxxxxxxxxxxxxxxxx" database = "xxxxxxxxxxxxxxxxxxxx" username = "xxxxxxxxxxxxxxxxxxxx" password = "xxxxxxxxxxxxxxxxxxxx" cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() ...other things....

    • and now play the game !

    0 讨论(0)
提交回复
热议问题