python django 原生sql 获取数据的例子

yipeiwu_com6年前Python基础

如下所示:

node2:/django/mysite/blog#cat views.py
1,
 
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# from django.shortcuts import render, render_to_response
from .models import *
# Create your views here.
from django.http import HttpResponse
from django.template import loader
import MySQLdb
 
def query():
  conn= MySQLdb.connect(
    host='localhost',
    port = 3306,
    user='root',
    passwd='1234567',
    db ='tlcb',
    )
  cur = conn.cursor()
  a=cur.execute("select title,body, DATE_FORMAT(timestamp,'%Y~%m~%d %k.%i.%s') A from blog_blogpost")
  info = cur.fetchall()
  return info
  cur.close()
  conn.close()
 
def archive(req):
 print 'aaaaaaaaaaaaaaaaaaaaaaaaaaa'
 print req
 print type(req)
 print req.GET
 print '#############################'
 print req.GET['aa']
 print req.GET['cc']
 print '#############################'
 print 'aaaaaaaaaaaaaaaaaaaaaaaaaaa'
# get all blogpost objects
 posts =query() 
 print posts
 print type(posts)
 #print blog_list
 template = loader.get_template('archive.html')
 context = {
 'posts':posts
 }
 print '------------------------------------------'
 print HttpResponse(template.render(context, req))
 print '------------------------------------------'
 return HttpResponse(template.render(context, req))
node2:/django/mysite/blog#
 
 
node2:/django/mysite/blog/templates#vi archive.html
node2:/django/mysite/blog/templates#
node2:/django/mysite/blog/templates#
node2:/django/mysite/blog/templates#
node2:/django/mysite/blog/templates#cat archive.html
{% extends "base.html" %} 
{% block content %}
   {% for post in posts %}
   <h2>{{ post.0 }}</h2>
   <p>{{ post.1 | date:"1,F jS"}}</p>
   <p>{{ post.2 }}</p>
   {% endfor %}
 {% endblock %}
 
 
 
(('dd', 'ddd', '2017~11~24 8.31.42'), ('66666666', '66666', '2017~11~24 8.35.25'), ('777777777', '77777777777', '2017~11~27 1.46.15'))
<type 'tuple'>
 
 
 
 
 
 
 在自定义 model 方法和模块级方法里,你可以自由的执行自定义SQL语句. 对象 django.db.connection 表示当前的数据库连接. 调用connection.cursor() 得到一个游标对象. 然后调用 cursor.execute(sql, [params])``以执行 SQL 语句, 使用 ``cursor.fetchone() 或cursor.fetchall() 得到结果集. 下面是一个例子:
def my_custom_sql(self): 
  from django.db import connection 
  cursor = connection.cursor() 
  cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) 
  row = cursor.fetchone() 
  return row 
 
    如果你的SQL语句改变了数据库中的数据 -- 比如你使用了 DELETE 或 UPDATE 语句. 你需要调用 connection.commit() 来使你的修改生效.
例子:
def my_custom_sql2(self): 
  from django.db import connection 
  cursor = connection.cursor() 
  cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz]) 
  connection.commit() 

以上这篇python django 原生sql 获取数据的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python数据结构之单链表详解

本文实例为大家分享了Python数据结构之单链表的具体代码,供大家参考,具体内容如下 # 节点类 class Node(): __slots__=['_item','_next'...

python使用电子邮件模块smtplib的方法

python使用电子邮件模块smtplib的方法

Smptp类定义:smtplib.SMTP(host[,port[,local_hostname[,,timeout]]]),作为SMTP的构造函数,功能是与smtp服务器建立连接,在连...

python绘制圆柱体的方法

python绘制圆柱体的方法

本文实例为大家分享了python绘制圆柱体示的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python import vtk # 参考的C++版本源码及解释...

python中numpy.zeros(np.zeros)的使用方法

翻译: 用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和类型的用0填充的数组; 参数:shape:形状 dtype:数据类型,可...

符合语言习惯的 Python 优雅编程技巧【推荐】

Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码,需要多看多学大牛们写的代码,github 上...