LoginSignup
8
12

More than 3 years have passed since last update.

PythonでODBC経由でデータベースからデータを取得(Access編)

Last updated at Posted at 2020-08-14

はじめに

先人の記事で十分ですが、自分用に。
あと、スポーツデータ解析コンペティションとかAccessでデータが来た記憶があるので、参加者のお役に立てば。

先人の記事

自分の例

環境

  • Windows 10 1909 64ビット版
  • Access 365 2002 32ビット版
    • 2002は(20)20年02月バージョンという意味です。2002年版ではありません😅。
  • Python 3.7.1 (Anaconda)
    • pyodbc 4.0.30
      • Anaconda付属のバージョンから、pipでアップデートしたものです
  • Visual Studio Code 1.48.0

下準備

「Microsoft Access データベース エンジン 2010 再頒布可能コンポーネント」をダウンロード&インストール
https://www.microsoft.com/ja-jp/download/details.aspx?id=13255
※ 上に書いたように、OSは64ビット、Accessは32ビットの環境ですが、再頒布可能コンポーネントは64ビット版(AccessDatabaseEngine_X64.exe)のほうを入れてうまくいきました

データベース

以下の内容を持つ、T_1 という名前のテーブルだけからなるデータベース

ID field1
1 テストの値

ソース

test.py
import pandas as pd
import pyodbc

# PCに入っているODBCドライバー一覧
print(pyodbc.drivers())
print()

# DBコネクションに用いる文字列
# 文字列内に「{}」とか「\」とかあるので、raw文字列を使うとよい
conn_str = (
    r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; ' +
    r'DBQ=(ドライブ名):\(フォルダー名)\ ~ \ファイル名.accdb;'
)

# DBを安全に開いたり閉じたりするのにwith文を使用
with pyodbc.connect(conn_str) as conn:

    # DataFrameを使う場合
    print('* DataFrameを使う場合')
    df = pd.io.sql.read_sql(r'select * from T_1', conn)
    print(df)
    print()

    print('* カーソルを使う場合')
    with conn.cursor() as cur:
        # 各テーブルについて
        for table_info in cur.tables(tableType='TABLE'):
            # select文で中身を表示
            # raw文字列とf記法の両方を使う場合は、「rf''」とする
            cur.execute(rf'select * from {table_info.table_name}')
            for row in cur.fetchall():
                print(row)

実行結果

['SQL Server', 'SQL Server Native Client 11.0', 'Microsoft Access Driver (*.mdb, *.accdb)', 'Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)', 'Microsoft Access dBASE Driver (*.dbf, *.ndx, *.mdx)', 'Microsoft Access Text Driver (*.txt, *.csv)']

* DataFrameを使う場合
   ID field1
0   1  テストの値

* カーソルを使う場合
(1, 'テストの値')

おわりに

以上です。

8
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
12