title: AWS Lambda function to connect to SQL Server with Python
body: <p>I've been stuck trying to connect to an SQL Server using AWS Lambda functions for a long while now. </p>
  
  <p>To do so i'm trying to use any library (tried with pyodbc, pypyodbc, etc), packaging everything into a zip file and uploading the code.</p>
  
  <p>The code is pretty much the same for every library, but the errors are different.</p>
  
  <p>The code: </p>
  
  <pre><code>import pypyodbc
  
  def lambda_handler(event, context):
      conn = pypyodbc.connect('DRIVER={SQL Server};'
                        'SERVER=1.1.1.1;'
                        'DATABASE=dbname;'
                        'UID=user;'
                        'PWD=pwd')
  
      cur = conn.cursor()
  
      cur.execute("SELECT * FROM Table")
  
      item_count = 0
  
      for row in cur:
          item_count += 1
  
      print(item_count)
  
      cur.close()
      conn.close()
  
      return item_count
  </code></pre>
  
  <p>Common issues that i have covered: 
   - I'm adding to the zip the project contents, not the folder.
   - I'm also adding to the zip file the libraries needed for the code to run.</p>
  
  <p><strong>If i try to use pyodbc</strong>, the zip i'm uploading looks like this:</p>
  
  <pre><code>.idea (dir)
  pyodbc (dir)
  lambda_function.py
  pyodbc.pyd
  </code></pre>
  
  <p>The error i get:</p>
  
  <pre><code>Unable to import module 'lambda_function': No module named pyodbc
  </code></pre>
  
  <p>After searching for quite a while about this, i couldn't find anything that helps. Only one comment that said that pyodbc needed to be instaled on a linux enviroment for the lambda function to work. But i don't have that Enviroment available, also i don't know if that will fix this.</p>
  
  <p><strong>If i try to use pypyodbc</strong>, the zip i'm uploading looks like this:</p>
  
  <p><img src="https://i.imgur.com/JYhCXTv.png" alt="image"></p>
  
  <p>The error i get:</p>
  
  <pre><code>module initialization error: 'ODBC Library is not found. Is LD_LIBRARY_PATH set?'
  </code></pre>
  
  <p>For this one i tried to install multiple python packages suggested by other stackoverflow posts (python-pyodb, unixodbc), but i failed every time.</p>
  
  <p>Then there was one comment around saying "Make sure to put native ODBC libraries under the lib folder in your zip deployment package"</p>
  
  <p>Maybe that is some help? I don't know how to get native ODBC libraries..</p>
  
  <p>Oh and one last thing. Both libraries work if i run them from my local machine. I can get access to the target server. It fails if i do it from the lambda function. </p>
  
  <p>Hopefully someone can help me and, apparently, the whole internet with this.</p>