0

我正在使用 pyodbc 处理存储在 MS-Access 数据库中的事件。每个月都是一个单独的文件/数据库,我想处理多个月的事件。

是否可以为包含多个月的视图创建游标,即数据库连接?

编辑 1:无需编写新数据库?(可能是 UNION VIEW 之类的东西?)

4

1 回答 1

4

您需要建立多个连接和游标,但您应该能够处理数据。

假设文件存储为month_1.mdb,month_2.mdbC:\access

# Set up each connection, must have a way to access each file's name
connect_string = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\access\\month_{}.mdb;"
# Assuming that you'll get the same data from each database
sql = "SELECT column_1, column_2 FROM table"
# Connect to each file
connections = [pyodbc.connect(connect_string.format(n)) for n in range(1, 12 + 1)]
# Create a cursor for each file
cursors = [conn.cursor() for conn in connections]
# Query each file and save the data
data = []
for cur in cursors:
  cur.execute(sql)
  data.extend(cur.fetchall())

好的,现在您拥有所有数据。您可以使用该模块创建一个内存数据库,sqlite3然后对其进行查询。

import sqlite3
# Create your temporary database
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
# Set up a place to hold the data fetched previously
_ = cur.execute("CREATE TABLE t(x INTEGER, y INTEGER)")
# Dump all the data into the database
for column_1, column_2 in data:
  _ = cursor.execute("INSERT INTO t VALUES (?, ?)", [column_1, column_2])
# Now you can run queries against the new view of your data
sql = "SELECT t.column_1, t.count(*) FROM t GROUP BY t.column_1"
于 2013-06-06T12:26:03.653 回答