Python 数据库工具类

[04/06注:待优化]

 


import pymysql
import readConfig

localReadConfig = readConfig.ReadConfig()

class myDB:

    def __init__(self):
        self.host = localReadConfig.getDBValue("host")
        self.username = localReadConfig.getDBValue("username")
        self.password = localReadConfig.getDBValue("password")
        self.port = int(localReadConfig.getDBValue("port"))
        self.database = localReadConfig.getDBValue("database")

    def connect_mysql(self):
        '''
        连接数据库
        '''
        #连接数据库
        self.db = pymysql.connect(host=self.host,port=self.port,user=self.username,password=self.password,database=self.database)
        #使用cursor()方法创建一个游标对象
        self.cursor = self.db.cursor()
        print("Connect DB successfully!")

    def executeSQL(self,sql):
        '''
        数据库操作:增删改查
        :param sql: insert / update / delete
        :return:
        '''
        try:
            self.connect_mysql()
            #使用execute()方法执行SQL语句
            self.cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()

    def QueryAll(self,sql):
        '''
        查询所有数据
        :param sql: select
        :return:
        '''
        self.connect_mysql()
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def __del__(self):
        '''
        关闭cursor和connection连接
        '''
        self.cursor.close()
        self.db.close()
        print("Database closed!")


test = myDB()
value = test.QueryAll("SELECT roomID FROM HT_LIVE_ZEGO_ROOM where status = 2")
for datas in value:
    for data in datas:
        data = int(data)

posted @ 2022-04-06 23:58  青山原  阅读(247)  评论(0编辑  收藏  举报