1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| def select(self, table, where_model, fields=None): """ 查询数据 :param table: :param where_model: 查询条件,类型为要查询的model实例 :param fields: 可选,需要查出的model的字段列表,默认查询model所有字段, :return: 满足条件的model的generator """ if fields is None: fields = where_model.get_field() where = '1=1' if where_model.__dict__: where = " and ".join(["%s='%s'" % (k, v) for k, v in where_model.__dict__.items()]) sql = "select %s from %s where %s order by id" % (",".join(fields), table, where) try: self._cur.execute(sql) result = self._cur.fetchall() if result: result = [dict((k, row[i]) for i, k in enumerate(fields)) for row in result] else: result = [] for data in result: yield Tools.dict_to_model(data, where_model) except Exception as e: self.close_db() logging.error("Execute '%s' error: %s" % (sql, traceback.format_exc())) logging.error(e)
def select_by_sql(self, model, sql): """ 查询数据 """ try: self._cur.execute(sql) result = self._cur.fetchall() if result: fields = model.get_field() result = [dict((k, row[i]) for i, k in enumerate(fields)) for row in result] else: result = [] for data in result: yield Tools.dict_to_model(data, model) except Exception as e: self.close_db() logging.error("Execute '%s' error: %s" % (sql, traceback.format_exc())) logging.error(e)
def select_one(self, table, where_model): """ 查询数据 :param table: :param where_model: 查询条件,类型为要查询的model实例 :return: 满足条件的model的generator """ fields = where_model.get_field() where = '1=1' if where_model.__dict__: where = " and ".join(["%s='%s'" % (k, v) for k, v in where_model.__dict__.items()]) sql = "select %s from %s where %s order by id limit 1" % (",".join(fields), table, where) try: self.execute(sql) result = self._cur.fetchall() if result: result = [dict((k, row[i]) for i, k in enumerate(fields)) for row in result] return Tools.dict_to_model(result[0], where_model) else: return None except Exception as e: self.close_db()
logging.error("Execute '%s' error: %s" % (sql, traceback.format_exc())) logging.error(e)
|