1. 程式人生 > 其它 >django執行自定義sql語句

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