django 链接多个数据库 并使用原生sql
作者:互联网
settings文件如下:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
"HOST": '127.0.0.1',
"PORT": 3306,
"USER": 'root',
'PASSWORD': "123456",
'NAME': 'analysis',
},
'analysis1': {
'ENGINE': 'django.db.backends.mysql',
"HOST": '127.0.0.1',
"PORT": 3306,
"USER": 'root',
'PASSWORD': "123456",
'NAME': 'analysis1',
}
}
查找Django的文档:
使用默认 default 数据库,
from django.db import connection
def my_custom_sql(self):
with connection.cursor() as cursor:
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row
如果有多个数据库,会默认使用 default,当你想使用指定的数据库连接时,引入的对象就变成了connections
from django.db import connections
def qwq():
with connections['analysis1'].cursor() as cursor:
# 查看所有表
cursor.execute("show tables")
# cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchall()
# 查询有多少数据 默认为第一张表
cursor.execute("select count(1) as c from %s" % t_name) # 查询有多少条数据
count_t = cursor.fetchone()
print(count_t)
# 查询表字段名及注释 默认为第一张表
sql_t_name = "select column_name,column_comment from INFORMATION_SCHEMA.Columns where table_name='{}'".format(
t_name)
cursor.execute(sql_t_name) # 查询有多少条数据
tables_data = cursor.fetchall()
————————————————
原文链接:https://blog.csdn.net/qq_37049050/article/details/85131514
标签:原生,execute,name,db,baz,django,cursor,sql 来源: https://blog.csdn.net/yutu75/article/details/119410459