Archive for 9月 26th, 2012

  1. Hello, ODBC(Python) World!

    Posted on 9月 26th, 2012 by cx20

    DB API

    ODBC(Open Database Connectivity)は、マイクロソフト社が提唱した DBMS 接続用の API 仕様である。
    DBMS の差異は ODBC ドライバによって吸収される為、ODBC の手順にしたがってプログラムを作成すれば、基本的な差異を意識せず、プログラムすることができる。

    ODBCドライバ ファイル
    Microsoft Access Driver (*.mdb) ODBCJT32.DLL
    Microsoft Text Driver (*.txt; *.csv) ODBCJT32.DLL
    Microsoft Excel Driver (*.xls) ODBCJT32.DLL
    Microsoft dBase Driver (*.dbf) ODBCJT32.DLL
    Microsoft ODBC for Oracle MSORCL32.DLL
    Microsoft Paradox Driver (*.db ) ODBCJT32.DLL
    SQL Server SQLSRV32.DLL
    Microsoft Access Driver (*.mdb, *.accdb) ACEODBC.DLL
    SQL Server Native Client 10.0 SQLNCLI10.DLL

    Python DB API は Python 向けの Database Interface(API)である。
    ODBC ドライバを介することで、様々な DBMS への接続が可能となっている。

    ソースコード(Python + DB API + ODBC + SQL Server)

    import pyodbc
     
    cn = pyodbc.connect("DRIVER={SQL Server};SERVER=(local);DATABASE=master;UID=sa;PWD=P@ssW0rd")
    cur = cn.cursor()
    cur.execute("SELECT 'Hello, ODBC World!' AS Message")
    rows = cur.fetchall()
     
    for row in rows:
        print "Message"
        print "-------------------"
        print row[0]
     
    cur.close()
    cn.close()

    実行方法(Windows)

    C:¥> python hello.py

    実行結果

    Message
    -----------------
    Hello, ODBC World!