环境说明:
python 3.7.4
java 1.8.0.40
前提条件:
安装python第三方库jaydebeapi、jpype1。安装时先安装jpype1再安装jaydebeapi.
安装jpype : pip install Jpype
安装JayDeBeApi : pip install JayDeBeApi
Python通过jdbc连接数据库的具体步骤:
1、配置参数:
jdbcString:Driver.class所在位置(com.cirrodata.Driver)
driverPath:jar包所在位置(D:/cirrodata/jdbc/test_JDBC.jar)
urlString:url连接串(jdbc:<数据库类型>://<host>:<post>/<数据库名>)
userName:数据库用户名
passWord:密码
2、导入第三方库jaydebeapi
import jaydebeapi
3、创建连接
conn = jaydebeapi.connect(jdbcString,urlString,[userName,passWord],driverPath)
4、对数据库进行操作
对数据库的操作区别只在于SQL语句。例如查询:
获取游标:curs = conn.cursor()
拼接SQL语句:sqlStr = 'select {} from {} where {}'.format(value, tableName, condition)
执行SQL语句:curs.execute(sqlStr)
获取查询返回结果:result = curs.fetchall()/result = curs.fetchone()
释放游标:curs.close()
如果不打算继续操作数据库后记得关闭连接:conn.close()
使用示例:
import jaydebeapi
url = 'jdbc:sp://127.0.0.1:3724/testdb'
user = 'test_user'
password = '123456_'
dirver = 'cirrodata.jdbc.driver.Driver'
jarFile = 'D:\jdbc\jdbc\cirrodataJdbcDriver.jar'
sqlStr = 'select count(1) from test_table'
conn = jaydebeapi.connect(dirver, url, [user, password], jarFile)
curs=conn.cursor()
curs.execute(sqlStr)
result=curs.fetchall()
print(result)
curs.close()
conn.close()