【磐维数据库】通过python访问磐维数据库
2024-10-24 09:35 狂澜与玉昆0950 阅读(100) 评论(0) 编辑 收藏 举报安装 psycopg2
1、下载并解压包
下载网址
1 | https://opengauss.org/zh/download/ |
解压包
1 | # 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 目录所在位置
1 2 | # python3 -c "from distutils.sysconfig import get_python_lib;print(get_python_lib())" /usr/lib/python3.6/site-packages |
2.2、拷贝
1 2 3 | # 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、切换到运行用户,设置环境变量
1 2 | $ echo "export LD_LIBRARY_PATH=/usr/lib/python3.6/site-packages/lib:$LD_LIBRARY_PATH" >> ~/.bashrc $ source ~/.bashrc |
使用固定ip访问数据库
1 2 3 4 5 6 7 8 9 10 11 | $ 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节点
1 | conn = psycopg2. connect (host= "ip1[,ip2,ip3]" ,port=port1, database =db, user = user , password = password ,target_session_attrs= "read-write" ) |
参考
1 | https://gitee.com/opengauss/openGauss-connector-python-psycopg2/#%E5%AE%89%E8%A3%85-psycopg2 |
我报路长嗟日暮,学诗谩有惊人句。
九万里风鹏正举。风休住,蓬舟吹取三山去!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步