V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2019-03-22 10:12:35 +08:00 · 1450 次点击
    这是一个创建于 1833 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    ORM 是接口方式调用,ORM 内部去做 SQL 语句生成,直接就有防止 SQL 注入的机制。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5452 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 01:33 · PVG 09:33 · LAX 18:33 · JFK 21:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.