您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)使用django怎么鏈接多個(gè)數(shù)據(jù)庫,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
settings文件如下:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db1': { # 配置第二個(gè)數(shù)據(jù)庫節(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ù)庫,會(huì)默認(rèn)使用 default,當(dāng)你想使用指定的數(shù)據(jù)庫連接時(shí),引入的對(duì)象就變成了connections !
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
之后再進(jìn)行操作。
補(bǔ)充知識(shí):Django多數(shù)據(jù)源接入類
from rest_framework.generics import GenericAPIView from rest_framework.response import Response from rest_framework import status from django.db import transaction from .contants import db_dict contants.py的內(nèi)容 ( import cx_Oracle import pymysql # 定義一個(gè)數(shù)據(jù)庫類型&引擎的字典, db_dict = {'mysql':pymysql,'Oracle':cx_Oracle} ) from .models import DataSystem,Rule class DBconnectView(GenericAPIView): __DBtype = db_dict def get(self,request,pk,rule_id): # 通過傳入的id進(jìn)行對(duì)應(yīng)的數(shù)據(jù)庫鏈接 self.datas = DataSystem.objects.get(pk=pk) self.url = self.datas.url self.username = self.datas.username self.password = self.datas.password_enc self.DBname = self.datas.name self.DBtype = self.__DBtype[self.datas.type] # 獲取check_code規(guī)則 self.ruledatas = Rule.objects.get(id=rule_id) self.check_code = self.ruledatas.check_code # db = __import__(self.DBtype) try: conn = self.DBtype.connect(host=self.url,user=self.username,password=self.password,database=self.DBname) # 鏈接成功后創(chuàng)建一個(gè)游標(biāo) cs_ms = conn.cursor() except Exception as e: raise e else: # 明顯的開啟事務(wù) with transaction.atomic(): # 在安全的地方,創(chuàng)建保存點(diǎn),將來操作數(shù)據(jù)庫失敗回滾到此 save_id = transaction.savepoint() try: # 獲取一個(gè)元組 db_ret = cs_ms.execute(self.check_code) except Exception as e: transaction.savepoint_rollback(save_id) raise e else: db_set = db_ret.fetchone() # transaction.savepoint_commit(save_id) finally: cs_ms.close() conn.close() return Response({'pk':pk,'rule_id':rule_id})
關(guān)于使用django怎么鏈接多個(gè)數(shù)據(jù)庫就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。