Loop through Microsoft Access queries with Python
<p>I need to loop through some queries of a Microsoft Access database (mdb).
Is there a possibility to do so with Python? (I am not familiar with Python.)</p>

<p>I was thinking of creating a list with the query names and then loop through it.</p>

<p>So far I have this:</p>

<pre><code># Import system modules (ArcGIS, Excel, Microsoft Access)
import arcpy
from arcpy import env
import csv
import pyodbc

# Set workspace

arcpy.env.workspace = r"\\mars\Skript\Connection to ERDE.XYZ.XX.sde"
MDB = r"\\mars\Konzept\auswertung_gdm.mdb"
</code></pre>

<blockquote>
  <p>I was thinking of creating a list with the query names and then loop through it.</p>
</blockquote>

<p>That's certainly possible. For example.</p>

<pre class="lang-python prettyprint-override"><code>query_names = ['Query1', 'Query2']
for query_name in query_names:
    sql = "SELECT * FROM [{}]".format(query_name)
    print(sql)
</code></pre>

<p>prints</p>

<pre class="lang-none prettyprint-override"><code>SELECT * FROM [Query1]
SELECT * FROM [Query2]
</code></pre>

<p>For your code the loop could execute each SELECT statement using a pyodbc <code>cursor</code> ...</p>

<pre class="lang-python prettyprint-override"><code>conn = pyodbc.connect(your_connection_string)  # e.g. "DRIVER=...;DBQ=...;"
crsr = conn.cursor()
crsr.execute(sql)
# do stuff with the results
crsr.close()
conn.close()
</code></pre>

<p>... retrieving the query results (via <code>crsr.fetchall()</code> or <code>crsr.fetchone()</code>) and processing them as required.</p>

python loops ms-access