安装 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标签:磐维,lib,python,psycopg2,数据库,site,usr,packages From: https://www.cnblogs.com/yuweijade/p/18498878