django中使用原生SQL语句
发布时间:2020-12-20 10:45:22 所属栏目:Python 来源:网络整理
导读: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
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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |