Jython - JDBC



Jython uses the zxJDBC package that provides an easy-to-use Python wrapper around JDBC. zxJDBC bridges two standards: JDBC is the standard platform for database access in Java, and DBI is the standard database API for Python apps.

ZxJDBC provides a DBI 2.0 standard compliant interface to JDBC. Over 200 drivers are available for JDBC and they all work with zxJDBC. High performance drivers are available for all major relational databases, including −

  • DB2
  • Derby
  • MySQL
  • Oracle
  • PostgreSQL
  • SQLite
  • SQL Server and
  • Sybase.

The ZxJDBC package can be downloaded from https://sourceforge.net/projects/zxjdbc/ or http://www.ziclix.com/zxjdbc/. The downloaded archive contains the ZxJDBC.jar, which should be added to the CLASSPATH environment variable.

We intend to establish database connectivity with MySQL database. For this purpose, the JDBC driver for MySQL is required. Download the MySQL J connector from the following link - https://dev.mysql.com/downloads/connector/j/ and include the mysql connector java-5.1.42-bin.jar in the CLASSPATH.

Login to the MySQL server and create a student table in the test database with the following structure −

Field Type Width
Name Varchar 10
Age Int 3
Marks Int 3

Add a few records in it.

Name Age Marks
Ravi 21 78
Ashok 20 65
Anil 22 71

Create the following Jython script as dbconnect.py.

url = "jdbc:mysql://localhost/test"
user = "root"
password = "password"
driver = "com.mysql.jdbc.Driver"
mysqlConn = zxJDBC.connect(url, user, password, driver)
mysqlConn = con.cursor()
mysqlConn.execute(“select * from student)
for a in mysql.fetchall():
   print a

Execute the above script from the Jython prompt. Records in the student table will be listed as shown below −

(“Ravi”, 21, 78)
(“Ashok”, 20, 65)
(“Anil”,22,71)

This explains the procedure of establishing JDBC in Jython.

Advertisements