{"id":16002,"library":"database-js","title":"database-js: Unified Database Access Interface","description":"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.","status":"active","version":"3.0.11","language":"javascript","source_language":"en","source_url":"https://github.com/mlaanderson/database-js","tags":["javascript","database-js","database-js-mysql","database-js-postgres","database-js-sqlite","database-js-adodb","database-js-firebase","database-js-ini","database-js-xlsx"],"install":[{"cmd":"npm install database-js","lang":"bash","label":"npm"},{"cmd":"yarn add database-js","lang":"bash","label":"yarn"},{"cmd":"pnpm add database-js","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for connecting to MySQL databases.","package":"database-js-mysql","optional":true},{"reason":"Required for connecting to PostgreSQL databases.","package":"database-js-postgres","optional":true},{"reason":"Required for connecting to SQLite databases.","package":"database-js-sqlite","optional":true},{"reason":"Required for connecting to Microsoft SQL Server databases.","package":"database-js-mssql","optional":true},{"reason":"Required for connecting to Firebase.","package":"database-js-firebase","optional":true},{"reason":"Required for connecting to CSV files.","package":"database-js-csv","optional":true},{"reason":"Required for connecting to Excel (XLSX) files.","package":"database-js-xlsx","optional":true},{"reason":"Required for connecting to JSON files.","package":"database-js-json","optional":true},{"reason":"Required for connecting to INI files.","package":"database-js-ini","optional":true},{"reason":"Required for connecting to ActiveX Data Objects (Windows only).","package":"database-js-adodb","optional":true}],"imports":[{"note":"The `Connection` class is a named export. While the documentation primarily shows CommonJS `require`, modern Node.js projects can use named ESM imports. Avoid default imports or importing the entire module without destructuring.","wrong":"import Connection from 'database-js';\n// or\nconst Connection = require('database-js');","symbol":"Connection","correct":"import { Connection } from 'database-js';\n// or\nconst { Connection } = require('database-js');"},{"note":"The `prepareStatement` method is accessed via an instantiated `Connection` object, not directly from the module export.","symbol":"prepareStatement (via Connection instance)","correct":"const conn = new Connection(connectionString);\nconst stmt = conn.prepareStatement(sql);"},{"note":"For developing custom drivers, the `Driver` base class might be needed, typically imported from a specific internal path, not the main package root. Most users will not need this.","wrong":"import { Driver } from 'database-js'; // Driver class is not a top-level export","symbol":"Driver (for custom drivers)","correct":"import { Driver } from 'database-js/lib/Driver'; // Example for custom driver development"}],"quickstart":{"code":"import { Connection } from 'database-js';\n// IMPORTANT: You must also install the specific driver package, e.g., 'npm install database-js-sqlite'\n\nasync function runDatabaseOperations() {\n  // Using SQLite as an example. Change the connection string\n  // and install the relevant driver for other databases.\n  const connectionString = \"sqlite:///path/to/test.sqlite\"; // Or mysql://user:password@localhost/test\n  const conn = new Connection(connectionString);\n\n  try {\n    // COMMAND: Create a table\n    await conn.prepareStatement(\n      \"CREATE TABLE IF NOT EXISTS city (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, population INTEGER)\"\n    ).execute();\n    console.log('Table created or already exists.');\n\n    // COMMAND: Insert data using a prepared statement\n    const insertStmt = conn.prepareStatement(\"INSERT INTO city (name, population) VALUES (?, ?)\");\n    await insertStmt.execute(\"Rio de Janeiro\", 6747815);\n    console.log('Inserted Rio de Janeiro.');\n\n    // QUERY: Select data using a prepared statement\n    const queryStmt = conn.prepareStatement(\"SELECT * FROM city WHERE name = ?\");\n    const results = await queryStmt.query(\"New York\"); // Assuming 'New York' might exist from previous runs\n    console.log('Query results for New York:', results);\n\n    // ANOTHER COMMAND: Update data\n    const updateStmt = conn.prepareStatement(\"UPDATE city SET population = population + ? WHERE name = ?\");\n    await updateStmt.execute(1, \"Rio de Janeiro\");\n    console.log('Updated Rio de Janeiro population.');\n\n    // QUERY: Select all data\n    const allCities = await conn.prepareStatement(\"SELECT * FROM city\").query();\n    console.log('All cities:', allCities);\n\n  } catch (reason) {\n    console.error('An error occurred:', reason);\n  } finally {\n    // CLOSING THE CONNECTION\n    await conn.close();\n    console.log('Connection closed.');\n  }\n}\n\nrunDatabaseOperations();","lang":"javascript","description":"This quickstart demonstrates how to establish a database connection, execute DDL, INSERT, UPDATE, and SELECT operations using prepared statements with the promise-based API, and properly close the connection. It highlights the unified interface across different database types."},"warnings":[{"fix":"Install the appropriate driver package for your database, e.g., `npm install database-js-sqlite`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the documentation for the specific `database-js` driver (e.g., `database-js-mysql` documentation) for the correct connection string format.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always `await` promise-returning methods or chain `.then()` and `.catch()` to handle successful completion and errors.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If encountering issues with `require()` or `import` statements, verify your module resolution settings in `package.json` (e.g., `\"type\": \"module\"`) and ensure you are using named imports `{ Connection }` rather than default imports for ESM, or destructuring for CJS.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always use `database-js` within a secure backend environment or a trusted, controlled desktop application (e.g., Electron). Never expose database connection details directly to a web browser client.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Run `npm install <driver-package-name>`, e.g., `npm install database-js-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.","error":"Error: No driver found for connection string: \"mysql://...\""},{"fix":"Ensure 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`).","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.","error":"TypeError: (0 , database_js__WEBPACK_IMPORTED_MODULE_0__.Connection) is not a constructor"},{"fix":"Always use `await` with `async` functions for database operations, or attach a `.catch()` handler to every Promise: `stmt.query().catch(error => console.error(error));`.","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.","error":"UnhandledPromiseRejectionWarning: Promise { <pending> }"},{"fix":"Verify that `Connection` is imported correctly and `new Connection(connectionString)` is called to create the connection object.","cause":"The `conn` object is not a valid `Connection` instance, likely due to an incorrect import or instantiation of the `Connection` class.","error":"TypeError: conn.prepareStatement is not a function"}],"ecosystem":"npm"}