python使用JDBC连接数据库

  1. 安装python第三方库jaydebeapi;

pip install jaydebeapi
  1. 将jar包放到指定位置;

python使用JDBC连接数据库_第1张图片
  1. 创建连接并对数据库进行操作;

import jaydebeapi
# 数据库配置
url = 'jdbc:dbcp://localhost:6688/test'
user = 'SYSDBA'
password = 'SYSDBA'
driver = 'com.dbcp.jdbc.Driver'
jarFile = 'F:/Python/testProject/lib/dbcp-jdbc-2.0.jar'

# 创建连接
conn = jaydebeapi.connect(
    jclassname=driver,
    url=url,
    driver_args=[user, password],
    jars=jarFile)

# 对数据库进行操作
# 获取游标
cursor = conn.cursor()
# 执行sql语句
sql = "select * from dba_tables;"
row_count = cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
print(result)
# 释放游标
cursor.close()
# 关闭数据库连接
conn.close()

注:创建连接部分各参数解释:摘抄自_init_.py:

def connect(jclassname, url, driver_args=None, jars=None, libs=None):
    """Open a connection to a database using a JDBC driver and return
    a Connection instance.

    jclassname: Full qualified Java class name of the JDBC driver.
    url: Database url as required by the JDBC driver.
    driver_args: Dictionary or sequence of arguments to be passed to
           the Java DriverManager.getConnection method. Usually
           sequence of username and password for the db. Alternatively
           a dictionary of connection arguments (where `user` and
           `password` would probably be included). See
           http://docs.oracle.com/javase/7/docs/api/java/sql/DriverManager.html
           for more details
    jars: Jar filename or sequence of filenames for the JDBC driver
    libs: Dll/so filenames or sequence of dlls/sos used as shared
          library by the JDBC driver
    """

你可能感兴趣的:(Python,数据库)