django 链接多个数据库 并使用原生sql
settings文件如下:
DATABASES = {
? ? 'default': {
? ? ? ? 'ENGINE': 'django.db.backends.sqlite3',
? ? ? ? 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
? ? },
? ? 'db1': { ? # 配置第二個(gè)數(shù)據(jù)庫(kù)節(jié)點(diǎn)名稱
? ? ? ? 'ENGINE': 'django.db.backends.oracle',
? ? ? ? 'NAME': 'devdb',
? ? ? ? 'USER': 'hysh',
? ? ? ? 'PASSWORD': 'hysh',
? ? ? ? 'HOST': '192.168.191.3',
? ? ? ? 'PORT': '1521',
? ? },
}
查找Django的文檔:
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
上述方法是設(shè)置中如果有多個(gè)數(shù)據(jù)庫(kù),會(huì)默認(rèn)使用 default,當(dāng)你想使用指定的數(shù)據(jù)庫(kù)連接時(shí),引入的對(duì)象就變成了connections !
from django.db import connections
with connections['db1'].cursor() as cursor:
? ? # Your code here...
之后再進(jìn)行操作。
————————————————
版權(quán)聲明:本文為CSDN博主「喝完這杯還有一箱」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_37049050/article/details/85131514
總結(jié)
以上是生活随笔為你收集整理的django 链接多个数据库 并使用原生sql的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 为什么广汽比东风好?
- 下一篇: 开车40分钟跑了54公里正常吗?