J. Doe
J. Doe

Reputation: 29

Connecting to an oracle database through Django

I would like to connect to an existing oracle database though Django and write a select statement to query the results. I am a beginner to Django and would like to know the steps to follow to achieve the same.

I did change the settings.py file to reflect the changes

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.oracle',
         'NAME': 'name',
         'USER': 'username',
         'PASSWORD': 'password',
         'HOST': 'host.com',
         'PORT': '1521',
  }
}

Upvotes: 0

Views: 9840

Answers (3)

Nishit Doshi
Nishit Doshi

Reputation: 51

You can follow the below steps to connect to the Oracle database using Django.

  1. Add database connection details in settings.py

If you are connecting through a service

DATABASES = {
    'default': {
       'ENGINE': 'django.db.backends.oracle',
       'NAME': 'host.db.com:1540/oracle_service.db.com',
       'USER': 'user',
       'PASSWORD': 'password',
   }
}

If you are connecting through SID

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'xe',
        'USER': 'a_user',
        'PASSWORD': 'a_password',
        'HOST': 'dbprod01ned.mycompany.com',
        'PORT': '1540',
    }
}

  1. Install the cx_Oracle library in your Django project.

  2. Go your application's views.py file and add the below code.

from django.http import JsonResponse
from django.db import connection
    
def process(request):
    with connection.cursor() as cursor:
         cursor.execute("select * from YOUR_TABLE")
         columns = [col[0] for col in cursor.description]
         return JsonResponse([
            dict(zip(columns, row))
            for row in cursor.fetchall()
         ], safe=False)

This API will output the query result in JSON format. Link to the official Django documentation

Upvotes: 1

LOrD_ARaGOrN
LOrD_ARaGOrN

Reputation: 4516

You need to change the entries like below in settings.py file.

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.oracle',
         'NAME': 'host.com:1521/dbname',
         'USER': 'username',
         'PASSWORD': 'password',
  }
}

Upvotes: 1

Hamfri
Hamfri

Reputation: 2219

The following should work.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.oracle',
        'NAME': 'db_user',
        'USER': 'shema_name',
        'PASSWORD': 'password',
        'HOST': 'ip_or_domain',
        'PORT': '1521',
    }
}

Upvotes: 0

Related Questions