django执行sql

Django与MySQL交互示例

http://docs.30c.org/djangobook2/chapter10/
def first_names(self, last_name):
cursor = connection.cursor()
cursor.execute("""
SELECT DISTINCT first_name
FROM people_person
WHERE last_name = %s""", [last_name])
return [row[0] for row in cursor.fetchone()]

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #引擎
'NAME': 'coin_02', # 库名
'USER': 'root', # 用户名
'PASSWORD': '123456', # 密码
'HOST': '127.0.0.1', # 地址
'PORT': '3306', # 端口
},
'test':{
'ENGINE': 'django.db.backends.mysql', #引擎
'NAME': 'test', # 库名
'USER': 'root', # 用户名
'PASSWORD': '123456', # 密码
'HOST': '127.0.0.1', # 地址
'PORT': '3306', # 端口
},

  官方文档;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)

转载于:https://www.cnblogs.com/lajiao/p/8910579.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值