database-js: Unified Database Access Interface
database-js provides a common, promise-based interface for SQL database access in JavaScript, inspired by the Java Database Connectivity (JDBC) API. It abstracts away the specifics of various underlying database drivers, allowing developers to interact with different databases (such as MySQL, PostgreSQL, SQLite, MS SQL Server, Firebase, CSV, Excel, JSON, and INI files) using a consistent API and connection string format. The library includes built-in support for prepared statements, even for drivers that don't natively offer them, and is designed to integrate seamlessly with ES7 async/await patterns. The current stable version is 3.0.11, and it receives regular maintenance updates for bug fixes. Its key differentiators include driver agnosticism via connection strings and a consistent promise-based API across heterogeneous data sources.
Common errors
-
Error: No driver found for connection string: "mysql://..."
cause The specific `database-js` driver package for the database type in the connection string (e.g., `database-js-mysql`) has not been installed.fixRun `npm install <driver-package-name>`, e.g., `npm install database-js-mysql`. -
TypeError: (0 , database_js__WEBPACK_IMPORTED_MODULE_0__.Connection) is not a constructor
cause This error typically occurs in bundled or transpiled environments (like Webpack or Babel) when trying to use CommonJS `require` syntax with a package that is treated as an ES Module, or when a named export is incorrectly imported as a default.fixEnsure you are using the correct named import: `import { Connection } from 'database-js';` for ESM, or `const { Connection } = require('database-js');` for CommonJS. Check your project's module resolution settings (`package.json#type`). -
UnhandledPromiseRejectionWarning: Promise { <pending> }cause A Promise returned by a `database-js` operation (like `query`, `execute`, or `close`) was not `await`ed or did not have a `.catch()` handler, leading to an unhandled rejection if an error occurred.fixAlways use `await` with `async` functions for database operations, or attach a `.catch()` handler to every Promise: `stmt.query().catch(error => console.error(error));`. -
TypeError: conn.prepareStatement is not a function
cause The `conn` object is not a valid `Connection` instance, likely due to an incorrect import or instantiation of the `Connection` class.fixVerify that `Connection` is imported correctly and `new Connection(connectionString)` is called to create the connection object.
Warnings
- gotcha database-js is a core interface library. You must explicitly install separate driver packages (e.g., `database-js-sqlite`, `database-js-mysql`) for the specific database type you intend to use. The core package itself has no built-in drivers.
- gotcha Connection strings are critical for specifying the database type, host, credentials, and other connection parameters. An incorrectly formatted connection string will lead to driver not found errors or connection failures.
- gotcha All database operations (query, execute, close) return Promises. Failing to use `await` or `.then().catch()` will result in unhandled promise rejections and operations not completing as expected, leading to difficult-to-debug asynchronous issues.
- breaking While not explicitly documented as a breaking change for `database-js` itself, historically, major version bumps (like v3) in Node.js libraries often introduce changes in module loading paradigms, potentially impacting how the library is imported (e.g., shifting primary support or default exports between CommonJS and ES Modules). Although the documentation shows CommonJS, modern tooling might expect ESM.
- gotcha This library is primarily designed for server-side (Node.js) applications. While some drivers might theoretically work in a browser environment (e.g., `database-js-sqlite` if compiled to WebAssembly), directly connecting to SQL databases from client-side JavaScript is a significant security risk and highly discouraged due to exposure of credentials and direct database access.
Install
-
npm install database-js -
yarn add database-js -
pnpm add database-js
Imports
- Connection
import Connection from 'database-js'; // or const Connection = require('database-js');import { Connection } from 'database-js'; // or const { Connection } = require('database-js'); - prepareStatement (via Connection instance)
const conn = new Connection(connectionString); const stmt = conn.prepareStatement(sql);
- Driver (for custom drivers)
import { Driver } from 'database-js'; // Driver class is not a top-level exportimport { Driver } from 'database-js/lib/Driver'; // Example for custom driver development
Quickstart
import { Connection } from 'database-js';
// IMPORTANT: You must also install the specific driver package, e.g., 'npm install database-js-sqlite'
async function runDatabaseOperations() {
// Using SQLite as an example. Change the connection string
// and install the relevant driver for other databases.
const connectionString = "sqlite:///path/to/test.sqlite"; // Or mysql://user:password@localhost/test
const conn = new Connection(connectionString);
try {
// COMMAND: Create a table
await conn.prepareStatement(
"CREATE TABLE IF NOT EXISTS city (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, population INTEGER)"
).execute();
console.log('Table created or already exists.');
// COMMAND: Insert data using a prepared statement
const insertStmt = conn.prepareStatement("INSERT INTO city (name, population) VALUES (?, ?)");
await insertStmt.execute("Rio de Janeiro", 6747815);
console.log('Inserted Rio de Janeiro.');
// QUERY: Select data using a prepared statement
const queryStmt = conn.prepareStatement("SELECT * FROM city WHERE name = ?");
const results = await queryStmt.query("New York"); // Assuming 'New York' might exist from previous runs
console.log('Query results for New York:', results);
// ANOTHER COMMAND: Update data
const updateStmt = conn.prepareStatement("UPDATE city SET population = population + ? WHERE name = ?");
await updateStmt.execute(1, "Rio de Janeiro");
console.log('Updated Rio de Janeiro population.');
// QUERY: Select all data
const allCities = await conn.prepareStatement("SELECT * FROM city").query();
console.log('All cities:', allCities);
} catch (reason) {
console.error('An error occurred:', reason);
} finally {
// CLOSING THE CONNECTION
await conn.close();
console.log('Connection closed.');
}
}
runDatabaseOperations();