Skip to content

Instantly share code, notes, and snippets.

@dmcghan dmcghan/db-config.js
Last active Jun 18, 2018

Embed
What would you like to do?
How to get, use, and close a DB connection using promises
module.exports = {
user: 'hr',
password: 'oracle',
connectString: 'localhost:1521/orcl',
poolMax: 20,
poolMin: 20,
poolIncrement: 0
};
const oracledb = require('oracledb');
function getEmployee(empId) {
return new Promise(function(resolve, reject) {
let conn; // Declared here for scoping purposes.
oracledb
.getConnection()
.then(function(c) {
console.log('Connected to database');
conn = c;
return conn.execute(
`select *
from employees
where employee_id = :emp_id`,
[empId],
{
outFormat: oracledb.OBJECT
}
);
})
.then(
function(result) {
console.log('Query executed');
resolve(result.rows[0]);
},
function(err) {
console.log('Error occurred', err);
reject(err);
}
)
.then(function() {
if (conn) {
// If conn assignment worked, need to close.
return conn.close();
}
})
.then(function() {
console.log('Connection closed');
})
.catch(function(err) {
// If error during close, just log.
console.log('Error closing connection', e);
});
});
}
module.exports.getEmployee = getEmployee;
const oracledb = require('oracledb');
const dbConfig = require('./db-config.js');
const employees = require('./employees.js');
oracledb.createPool(dbConfig)
.then(function() {
return employees.getEmployee(101);
})
.then(function(emp) {
console.log(emp);
})
.catch(function(err) {
console.log(err);
});
{
"name": "promises",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Dan McGhan <dan.mcghan@oracle.com> (https://jsao.io/)",
"license": "ISC",
"dependencies": {
"oracledb": "^1.13.1"
}
}
@dmcghan

This comment has been minimized.

Copy link
Owner Author

commented Jun 29, 2017

This gist is a demo app that shows how to get, use, and close a DB connection using promises. See the related blog post and the main post for the series for more details.

@srilatha93

This comment has been minimized.

Copy link

commented May 30, 2018

dae

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.