One of my first ever Jython scripts lets me get comma-separated values out of an RDBMS:
from java.lang import System
from java.sql import DriverManager, ResultSet
import csv
import cStringIO as StringIO
import sys
def doIt():
if System.getProperty("jdbc.drivers") is None or System.getProperty("jdbc2csv.query") is None:
try:
System.setProperty("jdbc2csv.url", sys.argv[1])
System.setProperty("jdbc2csv.query", sys.argv[2])
except IndexError:
print 'Usage: java -cp jython.jar:jdbc.jar -Djdbc.drivers=<jdbc.driver.class> -Djdbc2csv.query=<query> -Djdbc2csv.url-<jdbc.url> org.python.util.jython ' + sys.argv[0]
exit()
output = StringIO.StringIO()
conn = DriverManager.getConnection(System.getProperty("jdbc2csv.url"))
res = conn.createStatement().executeQuery(System.getProperty("jdbc2csv.query"))
meta = res.getMetaData()
header = ['row #']
for i in range(0, meta.getColumnCount()):
header.append(meta.getColumnName(i+1))
writer = csv.writer(output, quotechar = '"', quoting = csv.QUOTE_ALL, escapechar = '\\', delimiter = ',')
writer.writerow(header)
i = 0
while not res.isLast():
res.next()
i = i + 1
row = [i]
for column in range(1, meta.getColumnCount()+1):
row.append(res.getString(column))
writer.writerow(row)
conn.close()
print output.getvalue()
if __name__ == '__main__':
doIt()
One thing I can immediately see as a potential issue is utilising the optparse module to handle options in addition to JVM properties instead of sys.argv
. But, I await others ripping it apart.