DbTools.py 1.72 KB
from string import ascii_lowercase
from random import choice
import informixdb

# http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
CURSOR_NAME_COUNT = range(6)

def get_cursor_name():
    chars = string.ascii_lowercase
    return ''.join(random.choice(chars) for _ in CURSOR_NAME_COUNT)


class OtherEngine(object):
    def __init__(self, db_name, db_user, db_pass):
        self.db_name = db_name
        self.db_user = db_user
        self.db_pass = db_pass
        self.conn = None
        self.connected = False

    def get_connect(self):
        return informixdb.connect(self.db_name, user=self.db_user,
                password=self.db_pass)

    def connect(self):
        if self.connected:
            return self.conn
        self.conn = self.get_connect()
        self.connected = True
        return self.conn

    def disconnect(self):
        if self.connected:
            self.conn.close()
            self.connected = False

    def get_cursor(self):
        name = ''.join(choice(ascii_lowercase) for _ in CURSOR_NAME_COUNT)
        return self.conn.cursor(name, rowformat=informixdb.ROW_AS_DICT)
        #return self.conn.cursor(rowformat=informixdb.ROW_AS_OBJECT)

    def execute(self, sql):
        self.connect()
        cursor = self.get_cursor()
        cursor.execute(sql)
        cursor.close()

    def fetchone(self, sql):
        self.connect()
        cursor = self.get_cursor()
        cursor.execute(sql)
        r = cursor.fetchone()
        cursor.close()
        return r

    def fetchall(self, sql):
        self.connect()
        cursor = self.get_cursor()
        cursor.execute(sql)
        r = cursor.fetchall()
        cursor.close()
        return r