how to create a dynamic sql statement w/ python and mysqldb
- by Elias Bachaalany
I have the following code:
    def sql_exec(self, sql_stmt, args = tuple()):
        """
        Executes an SQL statement and returns a cursor.
        An SQL exception might be raised on error
        @return: SQL cursor object
        """
        cursor = self.conn.cursor()
        if self.__debug_sql:
            try:
                print "sql_exec: " % (sql_stmt % args)
            except:
                print "sql_exec: " % sql_stmt
        cursor.execute(sql_stmt, args)
        return cursor
    def test(self, limit = 0):
        result = sql_exec("""
            SELECT
                *
            FROM
                table
            """ + ("LIMIT %s" if limit else ""), (limit, ))
        while True:
            row = result.fetchone()
            if not row:
                break
            print row
        result.close()
How can I nicely write test() so it works with or without 'limit' without having to write two queries?