Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

How Flask Connects to Oracle DB (With Real Code)

 If you're learning Flask and want to connect it to an Oracle database, this post walks through a real, working example — line by line, in plain English.


Install the required packages.

pip install flask

pip install flask_sqlalchemy

pip install oracledb


We will user simple application code of data entry form which will insert data into database

The browser never talks directly to Oracle.

Instead:

  1. Browser sends data to Flask.
  2. Flask processes the request.
  3. SQLAlchemy creates database commands.
  4. python-oracledb sends those commands to Oracle.
  5. Oracle stores the data.

Flask Oracle DB flow 

Browser (form submit)
      ↓
Flask route (/contact)
      ↓
Python object (FlaskBlogContact)
      ↓
SQLAlchemy (translates to SQL)
      ↓
oracledb driver (speaks Oracle's protocol)
      ↓
Oracle Database


Below is my code , will explain you step by step 

from flask import Flask ,render_template,request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import oracledb
oracledb.init_oracle_client(lib_dir=r"C:\instantclient_21_11")
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] =
'oracle+oracledb://HR:HR@orcl.com:1521/?service_name=orcl'
db=SQLAlchemy(app)

class FlaskBlogContact(db.Model):
    __tablename__ = 'flask_blog_contact'

    contact_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(1000), nullable=False)
    email_address = db.Column(db.String(2000), unique=True)
    phone_number = db.Column(db.String(2000), nullable=False)
    message = db.Column(db.String(2000), nullable=False)
    creation_date = db.Column(db.Date, default=datetime.utcnow)




@app.route('/')
def disp():
 return render_template('index.html')
@app.route('/home')
def home():
 return render_template('index.html')
@app.route('/about')
def about():
 return render_template('about.html')

@app.route('/contact',methods=['GET','POST'])
def contact():
 if (request.method=='POST'):
   
   name= request.form.get('name')
   email= request.form.get('email')
   phone= request.form.get('phone')
   message= request.form.get('message')
   ''' Calling the table method FlaskBlogContact and map the colulmns '''
   entry=FlaskBlogContact(name=name,email_address=email,phone_number=phone,
message=message)
   db.session.add(entry)
   db.session.commit()

 return render_template('contact.html')

@app.route('/post')
def post():
 return render_template('post.html')
if __name__ == '__main__':
    app.run(debug=True)

1. The Imports

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import oracledb
  • Flask — the web framework itself.
  • flask_sqlalchemy — lets us talk to the database using Python objects instead of raw SQL.
  • oracledb — Oracle's official Python driver. This is the piece that actually knows how to speak to an Oracle database.

2. Setting Up the Oracle Client

oracledb.init_oracle_client(lib_dir=r"C:\instantclient_21_11")

Oracle databases need a special set of driver files called Instant Client to connect properly (this is different from MySQL or PostgreSQL, which don't need this step). This line tells Python: “here's where those driver files live on my computer.” Without it, the connection would fail.



3. The Database Connection String

app.config['SQLALCHEMY_DATABASE_URI'] = 'oracle+oracledb://hr:hr@orcl.com:1522/?service_name=orcl'

This one line has everything Flask needs to find and log into the database. Breaking it down:



db = SQLAlchemy(app)

This hands the connection info to SQLAlchemy, which becomes your toolkit for reading and writing data without writing raw SQL.


4. Defining a Table as a Python Class

class FlaskBlogContact(db.Model):
    __tablename__ = 'flask_blog_contact'

    contact_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(1000), nullable=False)
    email_address = db.Column(db.String(2000), unique=True)
    phone_number = db.Column(db.String(2000), nullable=False)
    message = db.Column(db.String(2000), nullable=False)
    creation_date = db.Column(db.Date, default=datetime.utcnow)

This is called an ORM model (Object-Relational Mapping). Instead of writing:

INSERT INTO flask_blog_contact (...)

…you write a Python class, and SQLAlchemy translates it into a table for you. Each attribute (name, email_address, etc.) becomes a column. primary_key=True marks contact_id as the unique row identifier, and nullable=False means that field can't be left empty.

5. The Routes (Pages of the Site)

@app.route('/')
def disp():
    return render_template('index.html')

Simple pages like /, /home, /about, and /post just render an HTML template — no database involved.

6. Where the Database Actually Gets Used

@app.route('/contact', methods=['GET','POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        phone = request.form.get('phone')
        message = request.form.get('message')

        entry = FlaskBlogContact(name=name, email_address=email, phone_number=phone, message=message)
        db.session.add(entry)
        db.session.commit()

    return render_template('contact.html')

This is the real action. Here's what happens step by step when someone submits the contact form:

  1. GET request → just shows the empty contact form (contact.html).
  2. POST request (form submitted) → Flask grabs each field with request.form.get(...).
  3. entry = FlaskBlogContact(...) creates a new Python object representing one row.
  4. db.session.add(entry) stages that row to be saved (like putting it in a shopping cart).
  5. db.session.commit() actually writes it to the Oracle database — this is the line that runs the INSERT behind the scenes.

You never wrote SQL yourself — SQLAlchemy converted your Python object into an Oracle INSERT statement automatically.


Enregistrer un commentaire

0 Commentaires