Reputation: 29
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
Reputation: 51
You can follow the below steps to connect to the Oracle database using Django.
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',
}
}
Install the cx_Oracle
library in your Django project.
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
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
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