django执行sql

  官方文档;http://docs.30c.org/djangobook2/chapter05
        from django.shortcuts import render_to_response
import MySQLdb

def book_list(request):
    db = MySQLdb.connect(user='me', db='mydb', passwd='secret', host='localhost')
    cursor = db.cursor()
    cursor.execute('SELECT name FROM books ORDER BY name')
    names = [row[0] for row in cursor.fetchall()]
    db.close()
    return render_to_response('book_list.html', {'names': names})

https://docs.djangoproject.com/en/2.0/topics/db/sql/
SQL语句 cursor.execute()使用占位符"%s",而不是直接在SQL中添加参数。如果您使用这种技

def GetList(request):
    from .conn_mysql import transaction,connections
    with connections['test'].cursor() as c:
        c.execute("select * from duanzi WHERE id=%s;",[2])
        # cursor.execute("select * from duanzi",[])
        # cursor.execute("insert into duanzi(content,createtime) VALUES ('aa','1518186153')",[])
        # transaction.commit_unless_managed()

        row=c.fetchone()
        # transaction.set_dirty()
        # cursor.close()
    return HttpResponse(row)

猜你喜欢

转载自www.cnblogs.com/lajiao/p/8910579.html
今日推荐