
import logging
import pymysql

class TMySql():

    def __init__(self, host, port, user, passwd, db):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.db = db
        self.sqls = []

    def connect(self):
        try:
            self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user, password=self.passwd,db=self.db)
            self.conn.autocommit(True)
            self.cursor = self.conn.cursor()
        except Exception as ex:
            logging.error("connect to [%s:%d] failed. Information: [%s]" % (str(self.host), int(self.port), str(ex)))


    def select(self, sql):
        try:
            self.cursor.execute(sql)
            return self.cursor.fetchall()
        except Exception as ex:
            logging.error("select sql [%s] failed. Information: [%s]" % (str(sql), str(ex)))

    def execute(self, sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as ex:
            logging.error("execute sql[%s] failed. Information: [%s]" % (str(sql), str(ex)))
            self.conn.rollback()
            return False
        return True

    def multiexec(self, sql):
        self.sqls.append(sql)

    def multicommit(self):
        try:
            for ss in self.sqls:
                self.cursor.execute(ss)

            self.conn.commit()
        except Exception as ex:
            self.conn.rollback()
            logging.error("Information[%s]" % (str(ex)))
            return False

        self.sqls = []
        return True

    def close(self):
        self.cursor.close()
        self.conn.close()
