conta's diary

思ったこと、やったことを書いてます。 twitter: @conta_

python + mysql やってみた

MySQLdbというモジュールを使ってみました。

実行環境

pc: mac osx lion
db: MAMP

インストール

brew install mysql
easy_install python-mysql

ソース

やっつけで書いたので、結構雑ですが。。。

import MySQLdb
import logging

def main():
    DB_NAME = 'spreadsheet'
    TABLE_NAME = 'test'
    
    connect = MySQLdb.connect(host='localhost', 
                          port=8889, 
                          unix_socket='/Applications/MAMP/tmp/mysql/mysql.sock', 
                          user='username',
                          passwd='pass', 
                          charset='utf8')
    connect.cursorclass = MySQLdb.cursors.DictCursor
    cursor = connect.cursor()
    
    # create db and table
    cursor.execute('create database if not exists ' + DB_NAME)
    cursor.execute('show databases')
    cursor.execute('create table if not exists ' + DB_NAME +' . '+ TABLE_NAME + 
                   '''
                   (
                    id int(5) NOT NULL,
                    name varchar(32) NOT NULL,
                    PRIMARY KEY (id)
                    )
                   ''')
    
    try:
        cursor.execute('insert into ' + DB_NAME +' . '+ TABLE_NAME +' (id, name) values (%s, %s)',
                       (3, 'test'))
    except MySQLdb.cursors.IntegrityError, msg:
        print 'IntegrityError'
        print msg
    
    connect.commit() 
    
    logging.debug(cursor.fetchall())
    cursor.execute('select * from ' + DB_NAME +' . '+ TABLE_NAME)
    print cursor.fetchall()
    cursor.close()
    
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()

insertは、データベースに挿入したあと
connect.commit()
をしないとDBに反映されないらしい。

おしまい!