温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

django中使用原生SQL语句

发布时间:2020-07-15 14:53:50 来源:网络 阅读:515 作者:AlunE 栏目:编程语言

views中代码;

# 有多个数据库时
from django.db import connections

# 傳入游标,得到字典結果集
def dictfetchall(cursor):
    "将游标返回的结果保存到一个字典对象中"
    desc = cursor.description
    return [
    dict(zip([col[0] for col in desc], row))
    for row in cursor.fetchall()
    ]

def seldata(request):
        sql ="SELECT TOP 100 * FROM EwData"
        conn = connections['MyDB']          #連接的數據庫
        cur = conn.cursor()                  #連接游標
        cur.execute(sql)                    #執行SQL語名
        data = dictfetchall(cur)               #把結果用字典返回
        return render(request, 'ewdata.html', {'ew': data,'fcol':data[0]})

html代码:

<table class="gridtable">
            <tr>
               {% for k in fcol %}
                    <th>{{ k }}</th>
                {% endfor %}
            </tr>
                {% for i in ew %}
                    <tr>
                                        {#  根据SQL中的字段名显示数据 #}
                    <td>{{ i.McNo }}</td>
                    <td>{{ i.SN }}</td>
                    <td>{{ i.Model }}</td>
                    <td>{{ i.Block }}</td>
                    <td>{{ i.Floor }}</td>
                    <td>{{ i.Line }}</td>
                    <td>{{ i.Wight }}</td>
                    <td>{{ i.TestTime }}</td>
                    <td>{{ i.Abortive }}</td>
                    <td>{{ i.Checker }}</td>
                    <td>{{ i.Multiple }}</td>
                    <td>{{ i.PackSN }}</td>
                    </tr>
                {% endfor %}
        </table>
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI