使用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

posted @ 2022-03-25 12:42  CodeYaSuo  阅读(919)  评论(0编辑  收藏  举报