view sqlex/model.py @ 3:5f1e1ac96aa7

stub works with SELECT
author Jeff Hammel <k0scist@gmail.com>
date Sat, 01 Apr 2017 09:19:22 -0700
parents 63a75d318b06
children 3a7f515571dc
line wrap: on
line source

import sqlite3

class SQLEx(object):
    """
    sqlite model
    https://docs.python.org/2/library/sqlite3.html
    """

    def __init__(self, db):
        self.db = db
        self.conn = sqlite3.connect(self.db)

    def __call__(self, sql, *args):
        c = self.conn.cursor()
        c.execute(sql, args)
        self.conn.commit()
        try:
            return c.fetchall()
        except Exception as e:
            raise e

    def __del__(self):
        self.conn.close()

    def tables(self):
        """
        returns table names in database
        """
        # http://stackoverflow.com/questions/82875/how-to-list-the-tables-in-an-sqlite-database-file-that-was-opened-with-attach

        sql = "SELECT name FROM sqlite_master WHERE type='table';"
        tables = self(sql)
        return sum([list(item) for item in tables], [])