推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
shimingzhoudf
V2EX  ›  Python

Python 操作数据库

  •  
  •   shimingzhoudf · Mar 22, 2019 · 2460 views
    This topic created in 2756 days ago, the information mentioned may be changed or developed.

    下面这段代码和使用 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 replies  •  2019-03-22 10:27:34 +08:00
    xpresslink
        1
    xpresslink  
       Mar 22, 2019
    这段代码就是直接裸 SQL 执行。这个相当于 ORM 的底层。
    用这个方式最重的是考虑有 SQL 注入的风险,前面的代码中要有防范措施。

    ORM 是接口方式调用,ORM 内部去做 SQL 语句生成,直接就有防止 SQL 注入的机制。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2759 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 03:44 · PVG 11:44 · LAX 20:44 · JFK 23:44
    ♥ Do have faith in what you're doing.