依赖
- jpype1=1.5.0
- jaydebeapi=1.2.3
- DmJdbcDriver18.jar
启动JVM
def start_jvm():jvm_path = jpype.getDefaultJVMPath()jar_path = ":".join([".....jar", # 需要python调用的其他jar包".../DmJdbcDriver18.jar" # 去达梦官网下载])Djava = "-Djava.class.path=" + jar_pathif not jpype.isJVMStarted():jpype.startJVM(jvm_path, "-ea", Djava, convertStrings=True) # 需要convertStrings,否则返回变量是java类型的,如java.lang.Integer,没法用python处理if not jpype.isThreadAttachedToJVM():jpype.attachThreadToJVM()
需要注意,在一个python主程序中,只能调用一次 startJVM
建立连接
def get_db_conn():host = password = username = port = database = jdbc_driver_path = ".../DmJdbcDriver18.jar"jdbc_class_name = "dm.jdbc.driver.DmDriver"url = f'jdbc:dm://{host}:{port}/{database}'conn = jaydebeapi.connect(jdbc_class_name, url, [username, password], jdbc_driver_path)return conn
这个连接是 DB-API 格式,遵循DB-API共同的使用形式:
cur = conn.cursor()
try:cur.execute(sql)conn.commit()
except Exception as e:conn.rollback()
finally:conn.close()
连接池
推荐: https://blog.csdn.net/weixin_37674052/article/details/131745391