pythonからMySQLに接続してSQLを実行する

2016.9.10

こんなかんじ。

# -*- coding: utf-8 -*-
import MySQLdb
class DataBase(object):
    """docstring for DataBase"""
    def __init__(self):
        self.connector = ""
        self.cursor = ""

    def connect(self):
        host='127.0.0.1'
        port = 3306
        db = 'データベース名'
        user = 'DBユーザー名'
        passwd = 'DBパスワード'
        charset = 'utf8'

        self.connector = MySQLdb.connect(host, user, passwd, db, port, charset)
        self.cursor = self.connector.cursor()

    def disconnect(self):
        self.cursor.close()
        self.connector.close()

    def execute(self, sql_string):
        self.cursor.execute(sql_string)
        return self.cursor.fetchall()

    def commit(self):
        self.connector.commit()

if __name__ == "__main__":
    foo = DataBase()
    foo.connect()

    result = foo.execute('select count(*) from tableA')
    foo.disconnect()

    for row in result:
        print row[0]

関連記事