瀚高数据库
目录
环境
文档用途
详细信息
环境
系统平台:N/A
版本:4.5
文档用途
本文介绍在HGDB使用sm3认证时,python使用psycopg2连接HGDB的方法。
详细信息
Python连接HGDB可以使用psycopg2、Django,Django是依赖psycopg2的,底层用的都是libpq,pip安装的psycopg2自带libpq。因此在一般情况下pip安装psycopg2后可以直接连接HGDB。在一些情况下HGDB需要使用sm3密码认证方式,此时使用psycopg2自带的libpq是无法连接HGDB的,报错:“authentication method 13 not supported”;可以按照以下方式处理。
Linux下psycopg2连接HGDB查阅文章:【python应用系统访问瀚高库(APP);ID:018380901】。
Windows参考以下几个方法:
方法一:更改数据库认证方式
条件允许的情况下,将HGDB的认证方式由sm3改为md5;一定确认好是否可以修改,修改时必须仔细操作。
方法二:自己编译psycopg2
1)由于pip安装的psycopg2自带libpq,因此使用“pip install --no-binary :all: psycopg2”安装,使之不自带libpq,安装完毕后,使用HGDB提供的libpq动态库。
2)将附件中的hgdb文件夹放在任意位置(路径建议只包含中文和数字),并配置环境变量,如:
cmd中验证pg_config可以访问到,如:
C:\Users\Highgo>pg_config
BINDIR = C:/Users/Highgo/highgo/bin
DOCDIR = C:/Users/Highgo/highgo/doc
HTMLDIR = C:/Users/Highgo/highgo/doc
INCLUDEDIR = C:/Users/Highgo/highgo/include
PKGINCLUDEDIR = C:/Users/Highgo/highgo/include
INCLUDEDIR-SERVER = C:/Users/Highgo/highgo/include/server
LIBDIR = C:/Users/Highgo/highgo/lib
PKGLIBDIR = C:/Users/Highgo/highgo/lib
LOCALEDIR = C:/Users/Highgo/highgo/share/locale
MANDIR = C:/Users/Highgo/highgo/man
SHAREDIR = C:/Users/Highgo/highgo/share
SYSCONFDIR = C:/Users/Highgo/highgo/etc
PGXS = C:/Users/Highgo/highgo/lib/pgxs/src/makefiles/pgxs.mk
CONFIGURE = --enable-thread-safety --enable-nls --with-ldap --enable-FDE --enable-license --with-openssl --with-ossp-uuid --with-libxml --with-libxslt --with-perl
VERSION = PostgreSQL 12.3
3)安装Microsoft C++ Build Tools工具,用于源码构建psycopg2。vs_BuildTools下载地址:https://download.visualstudio.microsoft.com/download/pr/67cb4c13-1e6d-4bf5-97ed-93636beebd7d/bbd9e99e837140cc7838ec63d0609c5e63ff43001cfa1e558b48db235f015237/vs_BuildTools.exe;选择需要的组件,如下:
安装过程较长,所占空间比较大。
4)卸载已安装的psycopg2;
5)编译构建psycopg2;
C:\Users\Highgo>pip install --no-binary :all: psycopg2
Collecting psycopg2
Using cached psycopg2-2.9.7.tar.gz (383 kB)
Skipping wheel build for psycopg2, due to binaries being disabled for it.
Installing collected packages: psycopg2
Running setup.py install for psycopg2 ... done
Successfully installed psycopg2-2.9.7
6)将附件hgdb中的lib和bin下的文件全部复制到python安装目录下的$PYTHON_HOME\Lib\site-packages\psycopg2下,如:
1691658583833.png
7)重新打开cmd,测试python连接数据库,python脚本如下:
import psycopg2
conn = psycopg2.connect(
host="192.168.17.75",
port="5867",
database="highgo",
user="sysdba",
password="password"
)
cur = conn.cursor()
cur.execute("SELECT * FROM tbl_sm3")
rows = cur.fetchall()
for row in rows:
print(row)
cur.execute("INSERT INTO tbl_sm3 (c1, c2) VALUES (%s, %s)", ("1", "2"))
conn.commit()
cur.close()
conn.close()
8)测试:
C:\Users\Highgo>cd C:\Users\Highgo\Python
C:\Users\Highgo\Python>python testDB.py
(1, '2')
(1, '2')
(1, '2')
(1, '2')
以上实现了sm3认证连接。
9)常见报错
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\u200e’ in position 13: ordinal not in range(128)
解决:chcp 65001