Using MySQL (using external jars)
To use MySQL, you will need to use an external jar file.
Using external jar files with jython is a bit tricky because it has to modify the classpath at runtime.
We're using a trick called "ClassPathHack".
Download MySQL connector
- Create a new directory (in your server's dir) called 'lib'
- Download mysql-connector (platform independent)
- Open the archive and extract 'mysql-connector-java-X.X.XX-bin.jar, save it as 'mysql-connector.jar' inside the 'lib' dir
Create ClassPathHack
Copy the script below and save it as 'mysqlhack.py' in your plugin's directory
import java.lang.reflect.Method
import java.io.File
import java.net.URL
import java.net.URLClassLoader
import jarray
from java.lang import Class
jarfile = "lib/mysql-connector.jar"
driver = "com.mysql.jdbc.Driver"
url = java.io.File(jarfile).toURL()
sysloader = java.lang.ClassLoader.getSystemClassLoader()
sysclass = java.net.URLClassLoader
method = sysclass.getDeclaredMethod("addURL", [java.net.URL])
method.setAccessible(1)
jarray.array([url], java.lang.Object)
method.invoke(sysloader, [url])
Class.forName(driver)
Connecting to MySQL
Make sure you have zxJDBC
installed, then use something like this:
import mysqlhack
from com.ziclix.python.sql import zxJDBC
mysql_database = "jdbc:mysql://localhost/db_name"
mysql_user = "john_doe"
mysql_pass = "secret"
conn = zxJDBC.connect(mysql_database, mysql_user, mysql_pass, "com.mysql.jdbc.Driver")
curs = conn.cursor()
curs.execute("SELECT * FROM users WHERE name = ?", "Jane Doe")
results = curs.fetchall()
The jython website has more info on zxJDBC.
Comments