记录下自己日常工作中经常使用的几个小工具类
- ###################
- #日志辅助类
- #################
- class Logger:
- LOG_DEBUG= "debug"
- LOG_DEBUG_FILE = "/tmp/debug.log"
- LOG_RELEASE = "release"
- LOG_RELEASE_FILE = "/tmp/release.log"
- def __init__(self, log_type):
- self._logger = logging.getLogger(log_type)
- if log_type == Logger.LOG_DEBUG:
- self._logFile = Logger.LOG_DEBUG_FILE
- elif log_type == Logger.LOG_RELEASE:
- self._logFile = Logger.LOG_RELEASE_FILE
- handler = logging.FileHandler(self._logFile)
- if log_type == Logger.LOG_DEBUG:
- formatter = logging.Formatter('%(asctime)s ********* %(message)s')
- else:
- formatter = logging.Formatter('%(message)s')
- handler.setFormatter(formatter)
- self._logger.addHandler(handler)
- self._logger.setLevel(logging.INFO)
- def log(self, msg):
- if self._logger is not None:
- self._logger.info(msg)
- ###################
- #数据库辅助类
- #################
- class DbHelper:
- def __init__(self, strHost, strUser, strPassword, strDataBase):
- self._conn = None #数据库连接对象
- self._host = strHost
- self._user = strUser
- self._password = strPassword
- self._database = strDataBase
- def connect(self):#连接数据库
- try:
- self._conn = MySQLdb.connect(host = self._host, user = self._user, passwd = self._password, db = self._database, charset = "utf8", use_unicode = True)
- except:
- self._conn = None
- def isConnected(self):#数据库连接是否成功
- return self._conn != None
- def getDataBaseName(self):#返回数据库名称
- return self._database
- def insert(self, sql):#增加记录
- new_id = -1
- if sql != "":
- cursor = self._conn.cursor()
- try:
- try:
- cursor.execute("set autocommit = 1")
- cursor.execute(sql)
- new_id = cursor.lastrowid
- except:
- new_id = -1
- finally:
- cursor.close()
- return new_id
- def query(self, sql):#删除记录或修改记录
- if sql != "":
- cursor = self._conn.cursor()
- try:
- try:
- cursor.execute("set autocommit = 1")
- cursor.execute(sql)
- except:
- pass
- finally:
- cursor.close()
- def fetch_rows(self, sql): #获取多个记录行
- result = None
- if sql != "":
- cursor = self._conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
- try:
- try:
- cursor.execute(sql)
- result = cursor.fetchall()
- except:
- result = None
- finally:
- cursor.close()
- return result
- def fetch_one(self, sql):
- result = None
- if sql != "":
- cursor = self._conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
- try:
- try:
- cursor.execute(sql)
- result = cursor.fetchone()
- except:
- result = None
- finally:
- cursor.close()
- return result
- def __del__(self):#对象析构时执行关闭动作
- self.close()
- def close(self):#关闭数据库连接
- if self._conn != None:
- self._conn.close()
- self._conn = None
2,php部分,一个数据库操作类。
- class db_mysql
- {
- private $connid = FALSE;
- function __construct($dbhost, $dbuser, $dbpwd, $dbname = null) {
- $this->sql_connect($dbhost, $dbuser, $dbpwd, $dbname);
- }
- function sql_connect($dbhost, $dbuser, $dbpwd, $dbname = null) {
- if ($this->connid) {
- mysql_close($this->connid);
- }
- if (!$this->connid = mysql_connect($dbhost, $dbuser, $dbpwd)) {
- $this->handleError('Can not connect to MySQL server. host: ' . $dbhost . ", user:" . $dbuser.", pwd:".$dbpwd);
- }
- mysql_query("set character_set_connection=utf8, character_set_results=utf8, character_set_client=binary", $this->connid);
- if ($dbname) {
- $this->sql_select_db($dbname);
- }
- }
- function sql_select_db($dbname) {
- if (!mysql_select_db($dbname, $this->connid)) {
- $this->handleError('Cannot use database ' . $dbname);
- }
- }
- function sql_query($sql) {
- if (!($res = mysql_query($sql, $this->connid))) {
- $this->handleError('MySQL Query Error', $sql);
- }
- return $res;
- }
- function sql_insert($sql) {
- $this->sql_query($sql);
- return mysql_insert_id();
- }
- function sql_fetch_rows($sql, $result_type = MYSQL_ASSOC) {
- $res = $this->sql_query($sql);
- $ret = array();
- while ($r = mysql_fetch_array($res, $result_type)) {
- $ret[] = $r;
- }
- mysql_free_result($res);
- return $ret;
- }
- function sql_fetch_one($sql, $result_type = MYSQL_ASSOC) {
- $res = $this->sql_query($sql);
- $ret = mysql_fetch_array($res, $result_type);
- mysql_free_result($res);
- return $ret;
- }
- function sql_fetch_one_cell($sql) {
- $ret = $this->sql_fetch_one($sql, MYSQL_NUM);
- return $ret[0];
- }
- function sql_fetch_column($sql, $keyField, $result_type = MYSQL_ASSOC) {
- $res = $this->sql_query($sql);
- $ret = array();
- while ($r = mysql_fetch_array($res, $result_type)) {
- if (isset($r[$keyField])) {
- $ret[] = $r[$keyField];
- }
- }
- mysql_free_result($res);
- return $ret;
- }
- function sql_fetch_singlemap($sql, $keyField, $result_type = MYSQL_ASSOC) {
- $res = $this->sql_query($sql);
- $ret = array();
- while ($r = mysql_fetch_array($res, $result_type)) {
- if (isset($r[$keyField])) {
- $ret[$r[$keyField]] = $r;
- }
- }
- mysql_free_result($res);
- return $ret;
- }
- function sql_fetch_multimap($sql, $keyField, $result_type = MYSQL_ASSOC) {
- $res = $this->sql_query($sql);
- $ret = array();
- while ($r = mysql_fetch_array($res, $result_type)) {
- if (isset($r[$keyField])) {
- $ret[$r[$keyField]][] = $r;
- }
- }
- mysql_free_result($res);
- return $ret;
- }
- function handleError($message = '', $sql = '') {
- $err = emptyempty($sql) ? '' : 'MySQL Query:' . $sql;
- $err .= 'MySQL Error:' . mysql_error();
- $err .= ', MySQL Errno:' . mysql_errno();
- $err .= ', Message:' . $message;
- error_log($err);
- }
- function __destruct() {
- if ($this->connid) {
- mysql_close($this->connid);
- }
- }
- }