How can I make automatize fetchall() calling in pyodbc without exception handling?
<p>I want to do automatic results fetching after every <strong>pyodbc</strong> query. In usual situation <code>cursor.fetchall()</code> calling raises a <code>ProgrammingError</code> exception if no SQL has been executed or if it did not return a result set (e.g. was not a SELECT statement). I want to do something like this:</p>

<pre><code>def execute(query, data):
    cursor.execute(query, data)
    cursor.commit()
    try:
      result = cursor.fetchall()
    except pyodbc.ProgrammingError:
      result =  None
    return result
</code></pre>

<p>Is there some way to make it possible without using exception handling (it works too slow if it used)?</p>

<p>Here's an example that might work for you, with a list of samples queries to run:</p>

<pre><code>sql_to_run = [
    "SELECT 10000",
    "SELECT 2 + 2",
    "",
    "SELECT 'HELLO WORLD'",
]

for sql in sql_to_run:
    rows = cursor.execute(sql)

    if cursor.rowcount:
        for row in rows:
            print(row)
</code></pre>

<p>Output:</p>

<pre><code>(10000, )
(4, )
('HELLO WORLD', )
</code></pre>

<p>Will that do the trick? Good luck!</p>

python pyodbc