使用django自带的connection
from django.conf import settings import django import pymysql pymysql.install_as_MySQLdb() INSTALLED_APPS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxx', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', 'PORT': '3306', } } settings.configure(DATABASES=DATABASES, INSTALLED_APPS=INSTALLED_APPS) django.setup()
在外部进行 import 该文件名称 如 django_connect
from django.db import connection
import django_connect from django.db import connection with connection.cursor() as cursor: sql = """ select * from base_indexinfo """ cursor.execute(sql) columns = [col[0] for col in cursor.description] datas = [dict(zip(columns, row)) for row in cursor.fetchall()] print(datas)
2022-03-25
本文来自博客园,作者:CodeYaSuo,转载请注明原文链接:https://www.cnblogs.com/hany-postq473111315/p/16054124.html