【磐維資料庫】透過python訪問磐維資料庫

狂澜与玉昆0950發表於2024-10-24

安裝 psycopg2

1、下載並解壓包

下載網址

https://opengauss.org/zh/download/

解壓包

# tar -zxvf openGauss-5.0.2-CentOS-x86_64-Python.tar.gz 

解壓安裝包後,會得到兩個目錄lib和psycopg2。lib是psycopg2依賴的libpq等C動態庫檔案。

2、將解壓後的lib和psycopg2目錄複製到Python直譯器的site-packages 下讓python可以索引到

2.1、查詢 site-packages 目錄所在位置

# python3 -c "from distutils.sysconfig import get_python_lib;print(get_python_lib())"
/usr/lib/python3.6/site-packages

2.2、複製

# cp -rp psycopg2 /usr/lib/python3.6/site-packages
# cp -rp lib /usr/lib/python3.6/site-packages
# chmod 755 /usr/lib/python3.6/site-packages/psycopg2

3、切換到執行使用者,設定環境變數

$ echo "export LD_LIBRARY_PATH=/usr/lib/python3.6/site-packages/lib:$LD_LIBRARY_PATH" >> ~/.bashrc
$ source ~/.bashrc

使用固定ip訪問資料庫

$ python3
Python 3.6.8 (default, Nov 16 2020, 16:55:22)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.
import psycopg2
conn = psycopg2.connect(database="testdb", user="testuser", password="testuser", host="192.168.100.10", port="1921")
cur = conn.cursor()
cur.execute("select * from test")
rows = cur.fetchall()
for row in rows:
    print("ID = ",row[0],"NAME = ",row[1])

輸出如下:

訪問資料庫primary節點

conn = psycopg2.connect(host="ip1[,ip2,ip3]",port=port1,database=db,user=user, password=password,target_session_attrs="read-write")

參考

https://gitee.com/opengauss/openGauss-connector-python-psycopg2/#%E5%AE%89%E8%A3%85-psycopg2

相關文章