分からんこと多すぎ

何故か就職できたので技術磨く。一人前の多重線形代数使いを目指しつつ、機械学習、データマイニングをやる

mysql-python(MySQLdb)を使ってみる

pythonRSSをもらってきているので、pythonMySQLを叩く。
MySQL - python入門から応用までの学習サイト
pythonのmysqldbの使い方メモ | taichino.com
API Documentation


  1. homebrewからmysql-pythonをもらってくる

    pip install MySQL-python

  2. MySQLのデータベースにアクセスする

    import MySQLdb
    connector = MySQLdb.connect(user="ユーザ名",passwd="パスワード",db="データベース名",charset="utf8")
    

  3. cursorで処理をする

    cursor = connector.cursor()
    cursor.execute('select * from テーブル名;')
    result = cursor.fetchall()
    for l in result:
      print l
    
    (1L, u'suger', 1L, 100L, u'', datetime.datetime(2000, 5, 24, 11, 11, 11))
    (2L, u'solt', 2L, 200L, u'', datetime.datetime(2013, 5, 24, 11, 11, 11))
    (3L, u'apple', 3L, 300L, u'', datetime.datetime(2013, 6, 24, 11, 11, 11))
    (4L, u'banana', 1L, 1000L, u'', datetime.datetime(2014, 5, 24, 11, 11, 11))
    (5L, u'\u30b9\u30a4\u30ab', 1L, 2000L, u'', datetime.datetime(2022, 5, 24, 11, 11, 11))
    (6L, u'\u725b\u4e73', 2L, 10000L, u'', datetime.datetime(2100, 5, 24, 11, 11, 11))

    カーソルの意味はこちら.要するに、テーブルを一行ずつ処理すること
    さらっと覚えるSQL&T-SQL入門(11):ストアドプロシージャの花形“カーソル”を使おう (1/3) - @IT
    フェッチの意味はこちら。カーソルがポインタみたいになってるので、その要素を取り出すこと。
    SQL実践講座(22):ストアドプロシージャによる繰り返し処理 - @IT

    1Lとかなっているのは、long型という意味。intに突っ込めばintになる。

  4. insertする

    cursor.execute('create table test2(id int, memo text);')
    cursor.execute("insert into test2 (id,memo) values (1,'memodesu');")
    connector.commit()
    

    insertはconnectorをcommitしないと反映されないので注意!
    こんなくだらない事に数時間悩んだ。

  5. 接続を切る

    cursor.close()
    connector.close()