django运行自定义sql语句

from django.http import HttpResponse,JsonResponse
from django.shortcuts import render

from django.db import connection

# Create your views here.

'''
import pymysql
pymysql.install_as_MySQLdb()



DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'hanyku',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    }
}
'''


def get_datas(sql):
    with connection.cursor() as cursor:
        cursor.execute(sql)
        columns = [col[0] for col in cursor.description]
        datas = [dict(zip(columns, row)) for row in cursor.fetchall()]
        return datas


def test_connection(request):
    if request.method == 'POST':

        sql = f"""
        select t.字段
        from 表 as t
        where 条件
        """
        datas = get_datas(sql)
        for data in datas:
            print(data['字段'])

        return HttpResponse('OK')
        
    else:

        return HttpResponse('OK')

2022-03-09 21:15:16

posted @ 2022-03-09 21:16  CodeYaSuo  阅读(190)  评论(0编辑  收藏  举报