how to create a dynamic sql statement w/ python and mysqldb

Posted by Elias Bachaalany on Stack Overflow See other posts from Stack Overflow or by Elias Bachaalany
Published on 2010-07-28T10:18:33Z Indexed on 2010/12/24 21:54 UTC
Read the original article Hit count: 268

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about mysql