Python3 数据库操作基本类

安     装: pip3  install  mysql-connector 
# -*- coding: utf-8 -*-

'''
Copyright (c) 2018, mersap
All rights reserved.

摘    要: base mysql api
创 建 者: mersap
创建日期: 2018-10-11
'''
import mysql.connector
class MyDB(object):
    """docstring for MyDB"""
    def __init__(self, host, user, passwd , db):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = db

        self.connect = None
        self.cursor = None
    def db_connect(self):
        """数据库连接
        """
        self.connect = mysql.connector.connect(host=self.host, user=self.user, passwd=self.passwd, database=self.db)
        return self
    def db_cursor(self):
        if self.connect is None:
            self.connect = self.db_connect()

        if not self.connect.is_connected():
            self.connect = self.db_connect()
        self.cursor = self.connect.cursor()
        return self
    def get_rows(self , sql):
        """ 查询数据库结果
        :param sql: SQL语句
        :param cursor: 数据库游标
        """

        self.cursor.execute(sql)
        return self.cursor.fetchall()
    def db_execute(self, sql):
        self.cursor.execute(sql)
        self.connect.commit()
    def db_close(self):
        """关闭数据库连接和游标
        :param connect: 数据库连接实例
        :param cursor: 数据库游标
        """
        if self.connect:
            self.connect.close()
        if self.cursor:
            self.cursor.close()

上一篇:python 获取服务器基本信息


下一篇:《Android程序设计》一第2章-2.0 Android开发之Java