# 使用官方的Ubuntu镜像作为基础镜像
FROM ubuntu:20.04
# 设置环境变量以避免交互式安装提示
ENV DEBIAN_FRONTEND=noninteractive
# 更新包列表并安装必要的软件包
RUN apt-get update && \
apt-get install -y \
build-essential \
curl \
apt-transport-https \
unixodbc \
unixodbc-dev \
odbcinst \
gnupg2 \
wget \
python3 \
python3-pip && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# 下载并安装MySQL ODBC驱动的deb包
# 8.0.21 适合Ubuntu 20.04
RUN wget https://downloads.mysql.com/archives/get/p/10/file/mysql-connector-odbc_8.0.21-1ubuntu20.04_amd64.deb && \
dpkg -i mysql-connector-odbc_8.0.21-1ubuntu20.04_amd64.deb && \
apt-get install -f -y && \
rm mysql-connector-odbc_8.0.21-1ubuntu20.04_amd64.deb
# 配置 ODBC 驱动
RUN echo "[MySQL ODBC 8.0 Unicode Driver]" > /etc/odbcinst.ini && \
echo "Description = MySQL ODBC 8.0 Unicode Driver" >> /etc/odbcinst.ini && \
echo "Driver = /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so" >> /etc/odbcinst.ini && \
echo "[MySQL ODBC 8.0 ANSI Driver]" >> /etc/odbcinst.ini && \
echo "Description = MySQL ODBC 8.0 ANSI Driver" >> /etc/odbcinst.ini && \
echo "Driver = /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8a.so" >> /etc/odbcinst.ini
# 配置 ODBC 数据源
RUN echo "[MySQLDataSource]" > /etc/odbc.ini && \
echo "Driver = MySQL ODBC 8.0 Unicode Driver" >> /etc/odbc.ini && \
echo "Server = localhost" >> /etc/odbc.ini && \
echo "Port = 3306" >> /etc/odbc.ini && \
echo "Database = testdb" >> /etc/odbc.ini && \
echo "User = root" >> /etc/odbc.ini && \
echo "Password = YOUR_PASSWORD" >> /etc/odbc.ini
# # 安装 MySQL 5.7
# RUN apt-get update && \
# apt-get install -y mysql-server-5.7 && \
# apt-get clean && \
# rm -rf /var/lib/apt/lists/*
# # 启动 MySQL 服务并设置 root 用户密码
# RUN service mysql start && \
# mysql -u root -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'your_password';" && \
# mysql -u root -p'your_password' -e "CREATE DATABASE testdb;"
# 设置默认命令
#CMD ["bash"]
# 安装 pyodbc 用于测试连接
RUN pip3 install pyodbc
# 添加测试脚本
COPY test_odbc.py /test_odbc.py
# 设置默认命令
CMD ["python3", "/test_odbc.py"]
Python测试脚本: import pyodbc
# 配置数据库连接 dsn = 'MySQLDataSource' user = 'root' password = 'YOUR_PASSWORD' database = 'testdb'
# 创建连接字符串 conn_str = f'DSN={dsn};UID={user};PWD={password};DATABASE={database}'
# 尝试连接到数据库 try: conn = pyodbc.connect(conn_str) print("Connected to the database successfully!") conn.close() except Exception as e: print(f"Failed to connect to the database: {e}") 标签:Python,ODBC,odbc,echo,etc,ini,&&,MySQL From: https://www.cnblogs.com/pccai/p/18203794