Python3資料庫操作基本類

mersap發表於2019-02-11
安     裝: 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()


相關文章