首页 > 解决方案 > 使用 python pyodbc 连接到 Docker 容器中的 Sybase 数据库的 utf-8 编码问题

问题描述

当我使用创建连接时pyodbc

connectionString = ('DRIVER='+driver+';SERVER='+server+';PORT='+port+';UID='+username+';PWD='+password+';DATABASE='+db_environment)
db_connection_dw = pyodbc.connect(connectionString)
cursor = db_connection_dw.cursor()
cursor.execute(sql_query_string)
print(cursor.fetchone())

CharField关于包含特殊字符的类型字段,我得到了奇怪的结果。例如,我得到 'M\x8adic' 而不是 'Mèdic'

Dockerfile

FROM python:3
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONIOENCODING=utf-8

ADD devartodbcase_amd64.deb /tmp/devartodbcase_amd64.deb
RUN apt-get clean && \
    apt-get update && \
    apt-get install -y locales locales-all && \
    locale-gen ca_ES.UTF-8 && \
    apt-get install -y gettext libgettextpo-dev g++ unixodbc unixodbc-dev libaio1 && \
    cd /tmp/ && dpkg -i devartodbcase_amd64.deb

ENV LANG ca_ES.UTF-8
ENV LC_ALL ca_ES.UTF-8

COPY ./requirements.txt /requirements.txt
RUN pip install --upgrade pip==20.0.2 && pip install -r /requirements.txt

RUN mkdir /app
WORKDIR /app
COPY ./app/ /app

要求.txt

Django==2.2.7
djangorestframework==3.10.3
django-filter==2.2.0
psycopg2==2.8.4
pyodbc==4.0.28

numpy==1.18.1
pandas==1.0.1

python-decouple==3.3
dj-database-url==0.5.0

django-widget-tweaks==1.4.5

SQLAlchemy==1.3.13

问题是驱动配置,Dockerfile配置引起的吗?提前致谢

标签: pythondockerutf-8dockerfilepyodbc

解决方案


您应该设置连接编码,因为 DB 客户端会导致某些默认 DB 服务器编码无法在您的脚本中正确解释。您可以在与 建立联系后执行此操作db_connection_dw.setencoding("utf-8")。请参阅以下手册https://github.com/mkleehammer/pyodbc/wiki/Unicode


推荐阅读