在Django 框架之外单独连接mysql 数据库

from django.db import connection
from django.conf import settings


settings.configure(
DATABASES={'default': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'xxxxxx',
# 'USER': 'xxxxx',
# 'PASSWORD': 'xxxxxx.',
# 'HOST': 'xxxxxx',
# # 'HOST': 'xxxxxx',
# 'PORT': '3306',
# 'OPTIONS': {'charset': 'utf8mb4'},
'ENGINE': 'django.db.backends.mysql',
'NAME': 'xxxxx',
'USER': 'xxxxx',
'PASSWORD': 'xxxxx',
'HOST': 'xxxxxxx',
'PORT': '3306',
'OPTIONS': {'charset': 'utf8mb4'},
}, },
)


class cursor(object):
def __init__(self):
self.cr = connection.cursor()

def query(self, sql):
self.cr.execute(sql)
res = self.cr.fetchall()
self.cr.close()
return res

def un_query(self, sql):
return self.cr.execute(sql)

# 测试代码

table = "adapter"
select_columns = ['`id`', '`code`', '`name`', '`show`', '`sort`',  '`enable`']

columns = ['`show`']
sql = "select %(columns)s from %(table)s where `show`!=0 order by sort " % {
"table": table, "columns": ", ".join(select_columns)}



sql3= "update adapter set `sort` =6, `enable` = 1  where code= 'ATLAS' "
sql4="insert into message_task (sms_phone,sms_template,content) values(18701202840,1324369,999999)"


# 执行
cr =cursor()
res = cr.query(sql4)



原文地址:https://www.cnblogs.com/DJRemix/p/11703341.html