在Docker中安装GaussDB的ODBC驱动并添加Python测试代码
# 使用官方的Ubuntu 20.04镜像作为基础镜像
FROM ubuntu:20.04
# 设置环境变量以避免交互式安装提示
ENV DEBIAN_FRONTEND=noninteractive
# 更新包列表并安装必要的软件包
RUN apt-get update && \
apt-get install -y \
wget \
curl \
gnupg2 \
apt-transport-https \
unixodbc \
unixodbc-dev \
odbcinst \
build-essential \
software-properties-common \
python3 \
python3-pip && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
# 下载并安装 GaussDB ODBC 驱动
RUN wget https://opengauss.obs.cn-south-1.myhuaweicloud.com/2.0.0/Ubuntu18.04/openGauss-odbc_2.0.0_amd64.deb && \
dpkg -i openGauss-odbc_2.0.0_amd64.deb && \
rm openGauss-odbc_2.0.0_amd64.deb
# 配置 ODBC 驱动
RUN echo "[GaussDB]" > /etc/odbcinst.ini && \
echo "Description = GaussDB ODBC Driver" >> /etc/odbcinst.ini && \
echo "Driver = /usr/local/gaussdb/lib/libodbcpsql.so" >> /etc/odbcinst.ini
# 配置 ODBC 数据源
RUN echo "[GaussDBDataSource]" > /etc/odbc.ini && \
echo "Driver = GaussDB" >> /etc/odbc.ini && \
echo "Servername = your_gaussdb_server" >> /etc/odbc.ini && \
echo "Port = 5432" >> /etc/odbc.ini && \
echo "Database = testdb" >> /etc/odbc.ini && \
echo "Username = your_user" >> /etc/odbc.ini && \
echo "Password = your_password" >> /etc/odbc.ini
# 安装 pyodbc 用于测试连接
RUN pip3 install pyodbc
# 添加测试脚本
COPY test_odbc.py /test_odbc.py
# 设置默认命令
CMD ["python3", "/test_odbc.py"]
import pyodbc
# 配置数据库连接
dsn = 'GaussDBDataSource'
user = 'your_user'
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}")