여러 연결과 커서를 만들어야하지만 데이터를 처리 할 수 있어야합니다.
C:\access
에 파일이 month_1.mdb
, month_2.mdb
등으로 저장되었다고 가정 해 봅니다.
# 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"
이렇게하면 각각에 대해 SQL이 실행됩니다. 즉, 결과 데이터에 여전히 중복 항목이있는 경우 GROUP BY를 사용할 때 데이터를 후행 처리해야 함을 의미합니다. 내가 원하는 것은 모든 데이터베이스에 대해 마치 하나 인 것처럼 SQL 쿼리를 실행할 수있게 해주는 커서입니다. – John
위와 같이 모든 데이터를 가져온 다음 결과를 새 데이터베이스로 덤프 한 다음 별도로 쿼리 할 수 있습니다. 파이썬에는 [sqlite3] (http://docs.python.org/3.3/library/sqlite3.html) 모듈이 포함되어 있습니다. – bbayles
대답을 편집하여이를 수행하는 방법의 예를 포함 시켰습니다. 새 Access 데이터베이스를 만드는 것을 피하고 쓸모없는 sqlite 데이터베이스를 사용할 수 있습니다. – bbayles