In previous posts, I demonstrated how to connect to an IBM Db2 database using PHP and Go. However, you can also connect to IBM Db2 from other languages. This post will walk you through an example using JavaScript.
NOTE: Before proceeding, ensure that you have a recent version of Node.js installed.
First, install the IBM Db2 package as below:
npm install ibm_db
Next, connect to the database and execute queries on it. Here’s an example:
const ibmdb = require('ibm_db');
const cn = "DRIVER={DB2 ODBC Driver};DATABASE=sample;UID=user;PWD=password;HOSTNAME=localhost;PORT=50000;PROTOCOL=TCPIP";
async function getBooks() {
try {
let conn = await ibmdb.open(cn);
console.log("Connection established:", conn);
let stmt = await conn.prepare("SELECT * FROM department LIMIT 0,3");
let result = await stmt.execute();
let data = await result.fetchAll();
console.log("Result:", data);
await result.close();
await stmt.close();
await conn.close();
} catch (e) {
console.error("An error occurred:", e);
}
}
getBooks();
You can now run the script with:
node example.js
The node-ibm_db
package exposes both synchronous and asynchronous APIs. This listing uses the asynchronous API, in particular the following functions:
open()
: Open a connection to the databaseprepare()
: Prepare a queryexecute()
: Execute a prepared queryfetchAll()
: Fetch all records of a result setclose()
: Close a connection to the database
Note that you can construct the DSN passed to open()
manually, as in the example above or, if you’re running on IBM Cloud, you can extract the DSN from the IBM Cloud VCAP_SERVICES
or CE_SERVICES
environment variables.
For a complete list of supported functions, refer to the API documentation.