Database-js2 Common Database Interface

1.4.2 · deprecated · verified Wed Apr 22

database-js2 is a JavaScript library providing a common, promise-based interface for accessing various database systems, inspired by Java's JDBC (Java Database Connectivity) pattern. It allows developers to interact with different databases (e.g., SQLite, MySQL, PostgreSQL) and even non-SQL data sources like Firebase, INI files, or Excel/CSV sheets using a unified API and connection string format. The library supports built-in prepared statements and integrates well with ES7 async/await syntax via Promises. This specific package, `database-js2`, is currently at version 1.4.2 but has been officially deprecated. All new feature development has ceased for this package, and future development and bug fixes are being published under the new `database-js` package (v3.x and above), which has claimed the original `database-js` npm package name.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to establish a connection to an SQLite database, create a table, insert data using prepared statements, query specific data, and properly close the connection using async/await.

const Connection = require('database-js2').Connection;
const fs = require('fs');
const path = require('path');

const dbPath = path.join(__dirname, 'test.sqlite');

// Create a dummy SQLite database file if it doesn't exist
if (!fs.existsSync(dbPath)) {
    fs.writeFileSync(dbPath, '');
}

// Ensure the SQLite driver is installed: npm install database-js-sqlite
// If using 'mysql' or 'postgres', install their respective drivers.

const conn = new Connection(`sqlite:///${dbPath}`);

async function runExample() {
    try {
        // Create a table if it doesn't exist
        await conn.prepareStatement("CREATE TABLE IF NOT EXISTS states (id INTEGER PRIMARY KEY, name TEXT)").query();
        console.log("Table 'states' ensured.");

        // Insert some data
        await conn.prepareStatement("INSERT INTO states (name) VALUES (?)").query("California");
        await conn.prepareStatement("INSERT INTO states (name) VALUES (?)").query("Texas");
        await conn.prepareStatement("INSERT INTO states (name) VALUES (?)").query("Florida");
        console.log("Data inserted.");

        // Query data with a prepared statement
        const statement = conn.prepareStatement("SELECT * FROM states WHERE name = ?");
        const results = await statement.query("Texas");
        console.log("Query Results for 'Texas':", results);

        // Close the connection
        await conn.close();
        console.log("Connection closed. Example finished.");
    } catch (reason) {
        console.error("Error during example execution:", reason);
        if (conn) {
            try {
                await conn.close();
            } catch (closeReason) {
                console.error("Error closing connection:", closeReason);
            }
        }
    }
}

runExample();

view raw JSON →