JayDeBeApi模块可让你从Python代码连接到使用Java JDBC数据库。它为该数据库提供了 Python DB-API v2.0。

1)、确认JayDeBeApi已经安装

[root@a02 ~]# pip3 list | grep JayDeBeApi
[root@a02 ~]# pip3 install JayDeBeApi
Looking in indexes: http://mirrors.cloud.aliyuncs.com/pypi/simple/
Collecting JayDeBeApi
  Using cached http://mirrors.cloud.aliyuncs.com/pypi/packages/ff/1f/6a627c9bd7dea13235b65fce0fff987507269d41f957c578031796f70319/JayDeBeApi-1.2.3-py3-none-any.whl (26 kB)
Requirement already satisfied: JPype1 in /usr/local/lib64/python3.6/site-packages (from JayDeBeApi) (1.3.0)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.6/site-packages (from JPype1->JayDeBeApi) (4.0.1)
Installing collected packages: JayDeBeApi
Successfully installed JayDeBeApi-1.2.3

2)、确认java环境已经安装

[root@a02 ~]# java -version
openjdk version "1.8.0_312"
OpenJDK Runtime Environment (build 1.8.0_312-b07)
OpenJDK 64-Bit Server VM (build 25.312-b07, mixed mode)

3)、复制JDBC驱动(gbasedbtjdbc_3.3.0_2.jar)到指定目录,如/root

[root@a02 ~]# ls -al gbasedbtjdbc_3.3.0_2.jar 
-rw-r--r-- 1 root root 2506640 Mar 31  2021 gbasedbtjdbc_3.3.0_2.jar

4)、编写测试程序TestJayDeBeApi.py,内容如下:

#!/usr/bin/python3
# filename: TestJayDeBeApi.py
import sys
import jaydebeapi

print("\nPython JayDeBeApi JDBC 测试程序开始运行.\n")
conn = jaydebeapi.connect("com.gbasedbt.jdbc.Driver",
                           "jdbc:gbasedbt-sqli://a02.gbasedbt.com:9088/testdb:GBASEDBTSERVER=gbase01;DB_LOCALE=zh_CN.utf8;CLIENT_LOCALE=zh_CN.utf8;IFX_LOCK_MODE_WAIT=60",
                           ["gbasedbt", "GBase123"],
                           "/root/gbasedbtjdbc_3.3.0_2.jar")

mycursor = conn.cursor()
mycursor.execute("drop table if exists company")

mycursor.execute("create table company(coid serial,coname varchar(255),coaddr text)")

mycursor.execute("insert into company(coname,coaddr) values (?,?)",('南大通用','天津市海泰绿色产业基地'))
mycursor.execute("insert into company(coname,coaddr) values (?,?)",('南大通用北京分公司','北京市朝阳区太阳宫'))

mycursor.execute("update company set coaddr = ? where coid = 1",('天津市普天创新园',))

mycursor.execute("select * from company")
rows = mycursor.fetchall()

for i, (coid, coname, coaddr) in enumerate(rows):
    print("公司ID: %d \t公司名称:%s\t公司地址: %s" % (coid, str(coname), coaddr))

mycursor.close()
conn.close()

print("\nPython JayDeBeApi JDBC 测试程序结束运行.\n")
sys.exit(0)

5)、执行测试

[root@a02 ~]# python3 TestJayDeBeApi.py 

Python JayDeBeApi JDBC 测试程序开始运行.

公司ID: 1       公司名称:南大通用      公司地址: 天津市普天创新园
公司ID: 2       公司名称:南大通用北京分公司    公司地址: 北京市朝阳区太阳宫

Python JayDeBeApi JDBC 测试程序结束运行.

更多推荐