Jython CLASSPATH, sys.path and JDBC drivers

前端 未结 2 2008
走了就别回头了
走了就别回头了 2020-12-05 15:45

How can I add JDBC drivers at runtime to Jython? Using CLASSPATH works, but using sys.path doesn\'t work with zxJDBC even though the class is imported fine and can be manipu

相关标签:
2条回答
  • 2020-12-05 16:05

    The solution is tricky, but everything is explained here.

    0 讨论(0)
  • 2020-12-05 16:06

    Looks like even the updated link does not work anymore (at least with jython-2.5.3b3).

    Here's a working version:

    def importJar(jarFile):
        '''
        import a jar at runtime (needed for JDBC [Class.forName])
    
        adapted from http://forum.java.sun.com/thread.jspa?threadID=300557
        Author: SG Langer Jan 2007 translated the above Java to Jython
        Author: seansummers@gmail.com simplified and updated for jython-2.5.3b3
    
        >>> importJar('jars/jtds-1.2.5.jar')
        >>> import java.lang.Class
        >>> java.lang.Class.forName('net.sourceforge.jtds.jdbc.Driver')
        <type 'net.sourceforge.jtds.jdbc.Driver'>
        '''
        from java.net import URL, URLClassLoader
        from java.lang import ClassLoader
        from java.io import File
        m = URLClassLoader.getDeclaredMethod("addURL", [URL])
        m.accessible = 1
        m.invoke(ClassLoader.getSystemClassLoader(), [File(jarFile).toURL()])
    
    if __name__ == '__main__':
        import doctest
        doctest.testmod()
    

    I keep this Gist updated with my production version.

    0 讨论(0)
提交回复
热议问题