Archive for 9月 24th, 2012

  1. Hello, DB API(Python) World!

    Posted on 9月 24th, 2012 by cx20

    DB API

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

    ソースコード(Python + DB API + MySQL)

    import MySQLdb
     
    cn = MySQLdb.connect(db="test", host="127.0.0.1", port=3306, user="root", passwd="P@ssW0rd")
    cur = cn.cursor()
    cur.execute("SELECT 'Hello, DB API 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, DB API World!