pymysql

使用上下文管理,操作数据库

import pymysql

from settings import db_info_one


class Connect(object):
    def __init__(self, host, password, port, user, database):
        self.conn = pymysql.connect(
            host=host, password=password, database=database, port=port, user=user
        )
        self.cursor = self.conn.cursor()

    def __enter__(self):
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.commit()
        self.conn.close()
        self.cursor.close()


if __name__ == '__main__':
    with Connect(**db_info_one) as db:
        db.execute("select * from article")
        print(db.fetchone())

settings

db_info_one = {
    "host": "localhost",
    "password": "123456",
    "port": 3306,
    "user": "root",
    "database": "industry"
}

 

posted @ 2019-01-11 21:21  猴里吧唧  阅读(61)  评论(0)    收藏  举报