今回はクラスの定義とデータベースに接続、開く、閉じるところまでやっています。
クラス名は SimpleDB 、ファイルを simpledb.py とします。
コンストラクタで接続情報を渡し、open 関数で接続、カーソルを変数に格納しておきます。
close 関数でカーソルを閉じ、接続を閉じます。
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import MySQLdb from collections import OrderedDict class SimpleDB(object): __host = None __user = None __password = None __database = None __cursor = None __connection = None def __init__(self, host, database, user, password): self.__host = host self.__database = database self.__user = user self.__password = password ## End def __init def open(self): con = MySQLdb.connect(self.__host, self.__user, self.__password, self.__database) self.__connection = con self.__cursor = con.cursor() ## End def open def close(self): self.__cursor.close() self.__connection.close() ## End def close ## End class if __name__ == '__main__': dbconfig = { "host": "localhost", "database": "<your database>", "user": "<your username>", "password": "<your secure password>", } try: db = SimpleDB(dbconfig['host'], dbconfig['database'], dbconfig['user'], dbconfig['password']) db.open() db.close() except Exception as e: print e.args