使用Python循环访问Microsoft Access查询

时间:2016-09-28 09:30:13

标签: python loops ms-access

我需要循环访问Microsoft Access数据库(mdb)的一些查询。 有没有可能用Python这样做? (我不熟悉Python。)

我正在考虑创建一个包含查询名称的列表,然后循环遍历它。

到目前为止,我有这个:

# 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"

2 个答案:

答案 0 :(得分:1)

  

我正在考虑创建一个包含查询名称的列表,然后循环遍历它。

这当然是可能的。例如。

query_names = ['Query1', 'Query2']
for query_name in query_names:
    sql = "SELECT * FROM [{}]".format(query_name)
    print(sql)

打印

SELECT * FROM [Query1]
SELECT * FROM [Query2]

对于您的代码,循环可以使用pyodbc cursor ...

执行每个SELECT语句
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()

...检索查询结果(通过crsr.fetchall()crsr.fetchone())并根据需要进行处理。

答案 1 :(得分:0)

如果您安装了Access,为什么不直接使用VBA进行此操作?

Public Sub GetMyObjectsList()
Dim db As Database
Dim Qry As QueryDef
Dim QryNames As String
Dim QryCount As Integer
Dim Tbl As TableDef
Dim TblNames As String
Dim TblCount As Integer
Set db = CurrentDb
QryCount = 0
TblCount = 0
For Each Qry In db.QueryDefs
 QryNames = QryNames & Qry.Name & ", "
 QryCount = QryCount + 1
Next
For Each Tbl In db.TableDefs
 If Tbl.Attributes = 0 Then 'Ignores System Tables
 TblNames = TblNames & Tbl.Name & ", "
 TblCount = TblCount + 1
 End If
Next
QryNames = QryNames & "TOTAL Query Count: " & QryCount
TblNames = TblNames & "TOTAL Table Count: " & TblCount
MsgBox QryNames
MsgBox TblNames
db.Close
Set db = Nothing
End Sub

或者,试试这个。

http://www.consultdmw.com/access-VBA-list-objects.htm