最終更新日:2016年9月10日

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

記事内に商品プロモーションを含む場合があります。

こんなかんじ。

# -*- 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]
pythonからMySQLに接続してSQLを実行するの商品をアマゾンで調べる。
macでuwsgiを動かしてテストページを表示してみた
sect: Pythons | lastmod: 2016-06-21 | pv: 5
pythonでOAuth認証をするときに便利なライブラリ
sect: Pythons | lastmod: 2016-05-29 | pv: 1
sudoを付けずに「pip install –upgrade pip」したらハマる
sect: Pythons | lastmod: 2016-05-29 | pv: 67
Flaskを始めるときの参考サイト
sect: Pythons | lastmod: 2017-02-12 | pv: 3
Pythonで再帰を使ってフィボナッチ数に挑戦してみた
sect: Pythons | lastmod: 2010-02-21 | pv: 3