python[Version 3.6] pymysql 简单封装

  • 上代码
import pymysql.cursors
import traceback

# Connect to the database
config = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '*****',
    'db': 'db_1',
    'charset': 'utf8mb4',
}


class MysqlUtils:
    def __init__(self, properties):
        properties['cursorclass'] = pymysql.cursors.DictCursor
        self.conn = pymysql.connect(**properties)
        self.cur = self.conn.cursor()

    def exe_update(self, sql):  # 更新,删除或插入操作
        sta = self.cur.execute(sql)
        self.conn.commit()
        return sta

    def exe_query(self, sql):  # 查找操作
        self.cur.execute(sql)
        return self.cur

    def conn_close(self):  # 关闭连接,释放资源
        self.cur.close()
        self.conn.close()


if __name__ == '__main__':
    mysql = MysqlUtils(config)
    # noinspection PyBroadException
    try:
        query = mysql.exe_query("select * from tb_1")
        print(query.fetchall())
    except Exception as e:
        traceback.print_exc()
    finally:
        mysql.conn_close()

你可能感兴趣的:(python[Version 3.6] pymysql 简单封装)