Over a million developers have joined DZone.

Node.js for Enterprise Solutions: Working With Oracle

In this article, I would like to explain how to quickly access Oracle in a NodeJS application. As an example, we will implement an exam score web application which we can query and update with exam data.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Motivation

Node.js is not a silver bullet for developing enterprise applications but it has a lot of advantages. Using Node, we can quickly write effective applications in much less time than usual.

In addition, in large companies, Oracle is often used as the relational database management system. So inevitably, we should get connections to Oracle in our NodeJS applications when we want to write NodeJS database applications.

In this article, I would like to explain how to quickly access Oracle in a NodeJS application. As an example, we will implement an exam score web application which we can query and update with exam data.

Let's begin...

Preliminary Preparation

First of all, we need to create an Oracle table.

CREATE TABLE ACCOUNT_SCORE
(
  ACCOUNT_NUMBER  NUMBER,
  SCORE           NUMBER
);

Insert any data in the table that's created above:

Insert into ACCOUNT_SCORE (ACCOUNT_NUMBER, SCORE)
 Values(4564552, 500);
Insert into ACCOUNT_SCORE (ACCOUNT_NUMBER, SCORE)
 Values(7834888, 600);
COMMIT;

We have one table that we will use in our NodeJS code:
Image title



Then we need to install the Node.js Oracle driver.

npm install oracledb

Please ensure to fulfill the prerequisites before you install the Oracle driver. The link is available here: https://www.npmjs.com/package/oracledb#installation.

Please ensure that you have already installed Python in your computer:

$ > python --version
Python 2.7.10

You can check the Oracle client library like this:

$ > echo %OCI_LIB_DIR%
C:\oracle\instantclient_12_1\sdk\lib\msvc\vc10

$ > echo %OCI_INC_DIR%
C:\ORA11G\oci\include

All dependencies at package.json:

{
  "name": "score_app",
  "version": "1.0.0",
  "description": "Score Update Screen",
  "main": "app.js",
"dependencies": {
    "body-parser": "^1.14.2",
    "cookie-parser": "^1.4.1",
    "express": "^4.13.4",
    "express-session": "^1.13.0",
    "hogan-express": "^0.5.2",
    "oracledb": "^1.5.0",
    "path": "^0.12.7",
    "soap": "^0.11.4"
  }
}

Let's Code

Create a simple HTML page to query exam score like this. (index.html)
Image title









<div class="container">
<div class="topDeck">
<div class="logo">
<h1>Screen of the Your Current Score</h1>
</div>
</div>
<div class="gallery">
<ul>
<form action="/sonuc">
Account Number: <input type="text" name="customerNo" value="" id="customerNo"><br><br>
<input type="submit" value="QUERY">
</form>
<br>
<p>You can click ""QUERY" button in order to learn your current account score</p>
</ul>
</div>
</div>

Let's write nodeJS express core code after creating the index HTML page.

'use strict'
var express = require("express");
var app = express();
var oracledb = require('oracledb');
var router = express.Router();
app.use('/', router);

app.listen(8080, function(){
    console.log('Score Update Screen is working on Port 8080');
});
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Welcome to Score Screen'});
});

Behind the "query" button, we write some NodeJS code in the "get" method in order to display the query results from the database.

router.get("/sonuc", function (req, res) {
    var customerNo = req.query.customerNo || 'Please fill correct number';
    var currentScore;
    oracledb.getConnection(
        {
            user          : "<db_schema_user>",
            password      : "<db_schema_password>",
            connectString : "<tns_or_alias>"
        },
        function(err, connection)
        {
            if (err) { console.error(err.message); 
                      res.render('sonuc', {result: 'Oracle error!'}); return; }

            connection.execute(
                "select score from account_score " +
                "where account_number=:0 ",
                customerNo.split(),  //for excample ->['6820393'],// bind value for :0
                function(err, result)
                {
                    if (err) {
                        console.error(err.message);
                        res.render('sonuc', {result: 'Oracle error!'});
                        return;
                    }
                    console.log(result.rows[0][0]);
                    currentScore = result.rows[0][0]||0;
                    res.render('sonuc', {result: currentScore, customerNo: customerNo});
                    doRelease(connection); //!!
                });
        });
});

After clicking the "query" button, Node.js directs us to the sonuc.html page. Exam score data that is collected in the Oracle database is at sonuc.html now.
Image title








Inside of sonuc.html:

<div class="gallery">
        <ul>
            <h2>Customer No: {{customerNo}} ,Result => {{result}} Current Score.</h2>
        </ul>
        <form action="/updateScore">
            <input type="text" name="nextScore" value="" id="nextScore">
            <input type="hidden" name="customerNo" value="{{customerNo}}">
            <input type="submit" value="Update Score">
        </form>
        <br>
        <form action="/">
            <input type="submit" value="Query again">
        </form>
</div>

If we want to update the exam score data that is collected by Node.js, we can click "Update Score" button to call Node.js "/updateScore" get method.

In NodeJs "/updateScore" get method:

router.get("/updateScore", function(req, res, next){
    var customerNo = req.query.customerNo;
    var nextScore = req.query.nextScore;
    oracledb.getConnection(
        {
            user          : "<db_schema_user>",
            password      : "<db_schema_password>",
            connectString : "<tns_or_alias>"
        },
        function(err, connection)
        {
            if (err) { console.error(err.message); 
                      res.render('sonuc', {result: 'Oracle error!'}); return; }

            connection.execute(
                "UPDATE account_score SET score = :score WHERE account_number = :accNo",
                {score: nextScore, accNo: customerNo},
                {autoCommit : true},
                function(err, result)
                {
                    if (err) {console.error(err.message);}
                    else {
                        console.log("Rows updated " + result.rowsAffected);
                        res.render('sonuc', {result: nextScore, customerNo: customerNo});
                        doRelease(connection);  //!!
                    }
                });
        });
});

Important Note: Please don't forget to release the Oracle connection after using the connection object.

// Release the connection
function doRelease(connection)
{
connection.release(
        function(err) {
            if (err) { console.error(err.message); }
        });
}


You can see all codes in my GitHub account project code link. (https://github.com/burhanorkun/nodejs_oracle_sample)

Conclusion

As a result, whenever I immediately need a database manipulation screen, the only thing is some NodeJS code that provides a lot of useful packages.  

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
nodejs ,oracle ,enterprise ,html

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}