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

时间:2022-04-18 04:26:38

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


settings.configure(
DATABASES={‘default‘: {
# ‘ENGINE‘: ‘django.db.backends.mysql‘,
# ‘NAME‘: ‘chatbot_seven‘,
# ‘USER‘: ‘chatbot‘,
# ‘PASSWORD‘: ‘yoquant123.‘,
# ‘HOST‘: ‘123.57.24.229‘,
# # ‘HOST‘: ‘10.9.0.179‘,
# ‘PORT‘: ‘3306‘,
# ‘OPTIONS‘: {‘charset‘: ‘utf8mb4‘},
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: ‘ai_manager‘,
‘USER‘: ‘ai‘,
‘PASSWORD‘: ‘yoquant‘,
‘HOST‘: ‘39.97.179.178‘,
‘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)