database-js
Wrapper for multiple databases with a JDBC-like connection
Database-js implements a common, promise-based interface for SQL database access. Inspired by Java, it uses connection strings to identify the database driver. Wrappers around native database drivers provide a unified interface to handle databases. Thus, you don't need to modify your code (except the connection string) to change your database! 😉
Database-js has built-in prepared statements, even if the underlying driver does not support them. It is built on Promises, so it works well with ES7 async code.
Contents
Install
npm install database-js
Drivers
See here how to add a new driver.
Usage
var Connection = require('database-js').Connection;
var conn =
new Connection("sqlite:///path/to/test.sqlite");
var stmt1 = conn.prepareStatement("SELECT * FROM city WHERE name = ?");
stmt1.query("New York")
.then( function (results) {
console.log(results);
} ).catch( function (reason) {
console.log(reason);
} );
var stmt2 = conn.prepareStatement("INSERT INTO city (name, population) VALUES (?, ?)");
stmt2.execute("Rio de Janeiro", 6747815)
.then( function() { console.log( 'Inserted.' ); } )
.catch( function(reason) { console.log('Error: ' + reason); } );
var stmt3 = conn.prepareStatement("UPDATE city SET population = population + ? WHERE name = ?");
stmt3.execute(1, "Rio de Janeiro")
.then( function() { console.log( 'Updated.' ); } )
.catch( function(reason) { console.log('Error: ' + reason); } );
conn.close()
.then( function() { console.log('Closed.'); } )
.catch( function(reason) { console.log('Error: ' + reason); } );
Async / await
Because database-js is built on Promises, it works very well with async/await. Compare the following code to the code from above. They accomplish the same thing.
const Connection = require('database-js').Connection;
(async () => {
let conn;
try {
conn = new Connection("mysql://user:password@localhost/test");
const stmt1 = conn.prepareStatement("SELECT * FROM city WHERE name = ?");
const results = await stmt1.query("New York");
console.log(results);
const stmt2 = conn.prepareStatement("INSERT INTO city (name, population) VALUES (?,?)");
await stmt1.execute("Rio de Janeiro", 6747815);
const stmt2 = conn.prepareStatement("UPDATE city SET population = population + ? WHERE name = ?");
await stmt1.execute(1, "Rio de Janeiro");
} catch (reason) {
console.log(reason);
} finally {
try {
await conn.close();
} catch (err) {
console.log(err);
}
}
})();
Basic API
See the source code for the full API.
class Connection {
prepareStatement(sql: string): PreparedStatement;
close(): Promise<void>;
isTransactionSupported(): boolean;
inTransaction(): boolean;
beginTransaction(): Promise<boolean>;
commit(): Promise<boolean>;
rollback(): Promise<boolean>;
}
class PreparedStatement {
query(...args: any): Promise<Array<any>>;
execute(... args): Promise<any>;
}
See also
License
MIT