简体   繁体   中英

How to connect to local sql server database from dockerized python app

I am trying to connect to a long-running SQL server database on my local machine from a dockerized python container, but I keep getting the error below. I will add all relevant code as well. I can confirm,m the username and password are both correct(I have verified 10+ times and set up a new account on the server and database with full rights as well).

I have scoured stack overflow and articles for the last day, but none have given me anything different, so I am hoping someone here will have some info that will point me in the right direction. Please let me know if you need any more info.

pyodbc.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]Login failed for user 'myusername'. (18456) (SQLDriverConnect)")

Here is my dockerfile

FROM python:3.7

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

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

RUN pip install --trusted-host pypi.python.org pyodbc==4.0.26 

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY src/. .

CMD ["python", "main.py"]

And here is main.py

import pyodbc

try:
  sql_connection = pyodbc.connect('Driver={FreeTDS};'
                                  'Server=host.docker.internal,1433;'
                                  'Database=mydatabasename;' 
                                  'UID=myusername;'
                                  'PWD=mypassword')
  sql_cursor = sql_connection.cursor()
  sql_cursor.execute("Select @@version")

  print(sql_cursor.fetchone())
finally:
  sql_cursor.close()
  sql_connection.close()

i would start with first trying to connect to this DB from inside the running docker container (via docker exec) using SQL client (psql, mysql-client whatever the DB you have) and connfirm you can do it. If not obviously smth on DB level doesn't allow the connection possibly only 127.0.0.1 is allowed in the DB settings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM