在Docker中安裝GaussDB的ODBC驅動並新增Python測試程式碼

pccai發表於2024-05-21

# 使用官方的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}")

相關文章