On Windows Server 2016, we are trying to connect over JDBC with a Jython script but it is giving following error:
java.lang.ClassNotFoundException: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
RazorSQL, on the same machine, connects without error using these settings:
Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver
Driver Location: \Program Files (x86)\RazorSQL\drivers\sqlserver\sqljdbc.jar
As a result, we set the CLASSPATH to same location with this command:
set CLASSPATH=C:\Program Files (x86)\RazorSQL\drivers\sqlserver\sqljdbc.jar
...but when running the code below - we still get the same ClassNotFound error.
This is our Python code:
jclassname = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
database = "our_database_name"
db_elem = ";databaseName={}".format(database) if database else ""
host = "###.##.###.###" # ip address
port = "1433"
user = "user_name"
password = "password"
url = (
jdbc:sqlserver://{host}:{port}{db_elem}"
";user={user};password={password}".format(
host=host, port=port, db_elem=db_elem,
er=user, password=password)
)
print url
driver_args = [url]
jars = None
libs = None
db = jaydebeapi.connect(jclassname, driver_args, jars=jars,
libs=libs)
This is how we are running our Python script:
C:\jython2.7.0\bin\jython.exe C:\path_to_our_script.py
How is that RazorSQL is connecting fine - but somehow Python cannot? How do we remove this CLASSPATH error?
You have to load the JARs at runtime using the system Classloader.
Please refer to this answer.
The following code snippet has been taken from this Gist.
def loadJar(jarFile): '''load a jar at runtime using the system Classloader (needed for JDBC) adapted from http://forum.java.sun.com/thread.jspa?threadID=300557 Author: Steve (SG) Langer Jan 2007 translated the above Java to Jython Reference: https://wiki.python.org/jython/JythonMonthly/Articles/January2007/3 Author: [email protected] simplified and updated for jython-2.5.3b3+ >>> loadJar('jtds-1.3.1.jar') >>> from java import lang, sql >>> lang.Class.forName('net.sourceforge.jtds.jdbc.Driver') <type 'net.sourceforge.jtds.jdbc.Driver'> >>> sql.DriverManager.getDriver('jdbc:jtds://server') jTDS 1.3.1 ''' from java import io, net, lang u = io.File(jarFile).toURL() if type(jarFile) <> net.URL else jarFile m = net.URLClassLoader.getDeclaredMethod('addURL', [net.URL]) m.accessible = 1 m.invoke(lang.ClassLoader.getSystemClassLoader(), [u]) if __name__ == '__main__': import doctest doctest.testmod()
Also look at - https://wiki.python.org/jython/JythonMonthly/Articles/January2007/3