One of the most powerful aspects of Jython is that you have native java objects and native python objects playing together in the same script. It also is one of the more confusing parts when you start trying to access python one in a java manner, or vice versa.

The application that I am scripting up with Selenium (via Jython) is for car dealerships. A new feature is that you can bundle a number of dealers as a ‘group’ to apply policies in a more convenient manner. Due to the nature of how the app is built, you cannot delete a group but can only mark it as inactive. This leads to the usual dirty data problem of automation. How can I make a group, if it is already created?.

The answer is of course to just be sneaky and nuke it from the database when the application isn’t looking. This code snippet make use of the connection I created here to first retrieve some information from a table, then use it to remove some information from a different one — all using prepared statements to ensure we are not susceptable to sql injection (not that this case is ripe for abuse, but it’s good to get in the habit of doing things securely).

def removeDealerGroup(self, dgid):
    # get the dealer group oid
    try:
        pstmt = self.connection.prepareStatement("select oid from group where group_id = ?")
        pstmt.setString(1, dgid)
        rset = pstmt.executeQuery()
        rset.next()
        oid = rset.getInt("group_oid")
    except java.sql.SQLException, e:
        if e.getMessage().find("Exhausted Resultset") != -1:
            return "Dealer Group %s does not exist" % dgid

    # get rid of the dealer group and associations
    msg = ""
    try:
        try:
            # remove the dealer association
            pstmt = self.connection.prepareStatement("delete from bank_group_assoc where oid = ?")
            pstmt.setInt(1, oid)
            rset = pstmt.executeQuery()
        except java.sql.SQLException, e:
            msg = "Could not remove dealer association"
            raise java.sql.SQLException, e
    except java.sql.SQLException, e:
        self.connection.rollback()
        #print e.getMessage()
        return msg