
下面这段代码和使用 ORM 操作有啥区别?
class DbCommonLibaray(object):
def executeQuery(self, sql): cursor = connection.cursor() # 获得一个游标(cursor)对象 cursor.execute(sql) rawData = cursor.fetchall() col_names = [desc[0] for desc in cursor.description] result = [] for row in rawData: objDict = {} # 把每一行的数据遍历出来放到 Dict 中 for index, value in enumerate(row): objDict[col_names[index]] = value result.append(objDict) return result def GetDTByPage(tableName, conditions, orderby, selectField="*", pageIndex=1, pageSize=20): if not selectField: selectField = "*" if conditions: cOnditions= "WHERE " + conditions sqlStart = str((pageIndex - 1) * pageSize) sqlEnd = str(pageIndex * pageSize) sqlQuery = "SELECT " + str(selectField) + " FROM " + tableName + " " + str(conditions) + " ORDER BY " + str( orderby) + " LIMIT " + str(sqlStart) + ", " + str(sqlEnd) returnValue = DbCommonLibaray.executeQuery(None, sqlQuery) return returnValue 1 xpresslink 2019-03-22 10:27:34 +08:00 这段代码就是直接裸 SQL 执行。这个相当于 ORM 的底层。 用这个方式最重的是考虑有 SQL 注入的风险,前面的代码中要有防范措施。 ORM 是接口方式调用,ORM 内部去做 SQL 语句生成,直接就有防止 SQL 注入的机制。 |