Skip to content

Instantly share code, notes, and snippets.

@dmcghan
Last active June 18, 2018 16:31
Show Gist options
  • Save dmcghan/adc1d985eab9b536566fb2ce4b8810fe to your computer and use it in GitHub Desktop.
Save dmcghan/adc1d985eab9b536566fb2ce4b8810fe to your computer and use it in GitHub Desktop.
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
Copy link
Author

dmcghan 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
Copy link

dae

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment