• Django当中的sql查询


    十二:在Django中使用sql
     
    关键字:
    connection     connections       transaction
    insert/create/update/delete/select/drop
     
    如果在models没有定义数据表名,将以app名加下划线加上定义的表名(自动转化为小写)
     
    查询时可以直接使用raws函数进行sql查询
     
    comment = Comment.objects.raw(select * from blog_comment)
     

    Django提供两种方式执行(performing)原始的SQL查询:

    (1)Manager.raw():执行原始查询并返回模型实例

    (2)Executing custom SQL directly:直接执行自定义SQL,这种方式可以完全避免数据模型,而是直接执行原始的SQL语句。

    raw() 方法自动通过查询字段映射到 model字段,并且是通过名称来匹配,这意味着我们可以使用SQL子句(clause)

    注意当输入查询字段的时候,不要漏了主键(id),否则会出错

     

    导入 form django.db import connection,transaction

    django.db.connection:代表默认的数据库连接
    django.db.transaction:代表默认数据库事务(transaction)
    connection.cursor(): 获得一个游标(cursor)对象
    cursor.execute(sql, [params]):执行SQL
    cursor.fetchone() 或者 cursor.fetchall():返回结果行

    如果执行修改操作,则调用transaction.commit_unless_managed()来保证你的更改提交到数据库。


     
    def sql(request):
    """
    ----------------------------------------------
    Function: 执行原始的SQL
    DateTime: 2013/x/xx
    ----------------------------------------------
    """
    from django.db import connection,transaction
    cursor = connection.cursor()#获得一个游标(cursor)对象
    #更新操作
    cursor.execute('update other_other2 set name ="李四" where id=%s',[3])#执行sql语句
    transaction.commit_unless_managed()#提交到数据库
    #查询操作
    cursor.execute('select * from other_other2 where id>%s',[1])
    raw = cursor.fetchone()#返回结果行 或使用 #raw = cursor.fetchall()
     
    #如果连接多个数据库则使用django.db.connections
    from django.db import connections
    _cursor = connections['other_database'].cursor()
    #如果执行了更新、删除等操作
    transaction.commit_unless_managed(using='other_databases')
    return render_to_response('other/sql.html',{'raw':raw})
     





  • 相关阅读:
    几种归一化方法的概念及python实现
    python 中几种基本的矩阵操作应用
    exec 命令简单用法 和 find 搭配用法示例
    使用git在github上创建新工程
    gcc编译参数详解概述
    此心不明,能有何为
    多个文件目录下Makefile的写法
    《高效能程序员的修炼》读后思考之写作的重要性
    音频格式RAW和PCM区别和联系
    SWIG 基本概念和入门
  • 原文地址:https://www.cnblogs.com/wuqingzangyue/p/5749451.html
Copyright © 2020-2023  润新知