Jython无法加载org.sqlite.JDBC / 类路径问题?

49 阅读2分钟

Jython是一个Java与Python之间的桥梁,它允许Python脚本访问Java类和库。但是,在使用Jython时,有时可能会遇到类路径问题,导致无法加载所需的Java类,从而引发ClassNotFoundException异常。

2、解决方案

在Jython中,可以通过在命令行中指定-Dpython.path=参数来添加额外的类路径。例如,如果需要加载位于Lib/sqlitejdbc.jar中的org.sqlite.JDBC类,可以在命令行中使用如下命令:

$ java -jar jython.jar -Dpython.path=Lib/sqlitejdbc.jar Application.py

通过这种方法,Jython能够找到并加载org.sqlite.JDBC类,从而解决ClassNotFoundException异常。

代码示例

以下是一个使用Jython连接SQLite数据库的代码示例:

import sys
from java.lang import Class
from java.sql  import DriverManager, SQLException

################################################################################

DATABASE    = "solarsys.db"
JDBC_URL    = "jdbc:sqlite:%s"  % DATABASE
JDBC_DRIVER = "org.sqlite.JDBC"

TABLE_NAME      = "planet"
TABLE_DROPPER   = "drop table if exists %s;"                      % TABLE_NAME
TABLE_CREATOR   = "create table %s (name, size, solar_distance);" % TABLE_NAME
RECORD_INSERTER = "insert into %s values (?, ?, ?);"              % TABLE_NAME
PLANET_QUERY = """
select name, size, solar_distance
from %s
order by size, solar_distance desc
""" % TABLE_NAME

PLANET_DATA = [('mercury' , 'small' ,    57),  # distance in million kilometers
               ('venus'   , 'small' ,   107),
               ('earth'   , 'small' ,   150),
               ('mars'    , 'small' ,   229),
               ('jupiter' , 'large' ,   777),
               ('saturn'  , 'large' ,   888),
               ('uranus'  , 'medium',  2871),
               ('neptune' , 'medium',  4496),
               ('pluto'   , 'tiny'  ,  5869),
               ]

################################################################################

def main():
    dbConn = getConnection(JDBC_URL, JDBC_DRIVER)
    stmt = dbConn.createStatement()
    try:
        stmt.executeUpdate(TABLE_DROPPER)
        stmt.executeUpdate(TABLE_CREATOR)
    except SQLException, msg:
        print msg
        sys.exit(1)

    if populateTable(dbConn, PLANET_DATA):
        resultSet = stmt.executeQuery(PLANET_QUERY)
        while resultSet.next():
            name = resultSet.getString("name")
            size = resultSet.getString("size")
            dist = resultSet.getInt   ("solar_distance")
            print "%-16.16s  %-8.8s  %4d" % (name, size, dist)

    stmt.close()
    dbConn.close()
    sys.exit(0)

################################################################################

def getConnection(jdbc_url, driverName):
    """
        Given the name of a JDBC driver class and the url to be used
        to connect to a database, attempt to obtain a connection to
        the database.
    """
    try:
        Class.forName(driverName).newInstance()
    except Exception, msg:
        print msg
        sys.exit(-1)

    try:
        dbConn = DriverManager.getConnection(jdbc_url)
    except SQLException, msg:
        print msg
        sys.exit(-1)

    return dbConn

################################################################################

def populateTable(dbConn, feedstock):
    """
        Given an open connection to a SQLite database and a list of tuples
        with the data to be inserted, insert the data into the target table.
    """
    try:
        preppedStmt = dbConn.prepareStatement(RECORD_INSERTER)
        for name, size, distance in feedstock:
            preppedStmt.setString(1, name)
            preppedStmt.setString(2, size)
            preppedStmt.setInt   (3, distance)
            preppedStmt.addBatch()
        dbConn.setAutoCommit(False)
        preppedStmt.executeBatch()
        dbConn.setAutoCommit(True)
    except SQLException, msg:
        print msg
        return False

    return True

################################################################################
################################################################################

if __name__ == '__main__':
    main()

在这个代码示例中,我们首先导入必要的库,然后定义了数据库连接信息和SQL语句。接下来,我们通过getConnection()函数获取数据库连接,并使用executeUpdate()函数来创建表和插入数据。最后,我们使用executeQuery()函数来查询数据并打印结果。