Connect docker python to SQL server with pyodbc

后端 未结 7 2015
迷失自我
迷失自我 2020-11-28 08:50

I\'m trying to connect a pyodbc python script running in a docker container to login to a MSSQL database I have tried all sorts of docker files, but not been able to make th

7条回答
  •  抹茶落季
    2020-11-28 09:33

    Running through this recently I found it was necessary to additionally include the following line (note that it did not build without this step):

    RUN apt-get install --reinstall build-essential -y

    The full Dockerfile looks as follows:

    # parent image
    FROM python:3.7-slim
    
    # install FreeTDS and dependencies
    RUN apt-get update \
     && apt-get install unixodbc -y \
     && apt-get install unixodbc-dev -y \
     && apt-get install freetds-dev -y \
     && apt-get install freetds-bin -y \
     && apt-get install tdsodbc -y \
     && apt-get install --reinstall build-essential -y
    
    # populate "ocbcinst.ini"
    RUN echo "[FreeTDS]\n\
    Description = FreeTDS unixODBC Driver\n\
    Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so\n\
    Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so" >> /etc/odbcinst.ini
    
    # install pyodbc (and, optionally, sqlalchemy)
    RUN pip install --trusted-host pypi.python.org pyodbc==4.0.26 sqlalchemy==1.3.5
    
    # run app.py upon container launch
    CMD ["python", "app.py"]
    

    Here's one way to then actually establish the connection inside app.py, via sqlalchemy (and assuming port 1433):

    import sqlalchemy as sa
    args = (username, password, server, database)
    connstr = "mssql+pyodbc://{}:{}@{}/{}?driver=FreeTDS&port=1433&odbc_options='TDS_Version=8.0'"
    engine = sa.create_engine(connstr.format(*args))
    

提交回复
热议问题