forked from masteroftime/Python-Plugin-Loader
-
Notifications
You must be signed in to change notification settings - Fork 3
Using MySQL (using external jars)
jomo edited this page Jul 24, 2014
·
1 revision
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".
- 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
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)
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.