Skip to content

Examples Pools

Thiago Delgado Pinto edited this page Jun 5, 2021 · 3 revisions

Connection pools are now available, but should be considered beta. Two types of connection pools are available, static and dynamic. Static pools share a common pooling mechanism keyed to the connection URL. Thus creating a new StaticPool with the same URL forces it to share connections with existing pools that have the same connection URL. Dynamic pools do not share the pooling mechanism, so creating a new DynamicPool always allocates new connections.

Drivers that need special handling for use in a pool can implement a static pool function which is called after instantiating the pooled connection.

var Pool = require('database-js2').StaticPool; 

var pool = new Pool('database-js-mysql://my_secret_username:my_secret_password@localhost:3306/my_top_secret_database', 10);
var connection = pool.getConnection();

...

await connection.close(); // just releases the connection to the pool

...

await pool.close(); // actually closes all the connections and empties the pool

Example:

// test.js ---> It can be execute with node test.js after installing database-js-sqlite
var Pool = require('.').DynamicPool;
var args = process.argv.slice(2);

if (args.length < 1) { args.push('South Dakota'); }

( async () => {
    let pool = new Pool("sqlite:///test.sqlite");
    let connection = pool.getConnection();
    let statement, results;
    try {
        statement = await connection.prepareStatement("SELECT * FROM states WHERE State = ?");
        results = await statement.query(args[0]);
        console.log(results);
    } catch (err) {
        console.log(err);
    } finally {
        await pool.close();
    }
} )();