JavaScript Database Object
The JavaScript environment provide a global property named db that provide access to the current database with the following functionality:
// Properties
db.connectionInfo;
// Methods
async db.query(sql, parameters) {}
Query example
Select table records
First parameter is the SQL statement. Second (optional) parameter is the statement parameters.
const result = await db.query(
`SELECT col FROM tbl WHERE col = 'test'`
)
// [{ col: 'test' }]
// Single parameter
const result = await db.query(
'SELECT col FROM tbl WHERE col = ?',
'test'
)
// [{ col: 'test' }]
// Multiple parameters within an array.
const result = await db.query(
'SELECT col FROM tbl WHERE col in (?,?)',
['one','two']
)
// [{ col: 'one' }, { col: 'two' }]
// Named parameters
const result = await db.query(
'SELECT col FROM tbl WHERE col = :x',
{ 'x': 'test' }
)
// [{ col: 'test' }]
View QUERY result
View query records result
// Print query result as JSON string
console.log(result);
// Print query result with a table grid
console.table(result);
RUN example
Update statements result
const result = await db.query(
'INSERT INTO tbl VALUES ("test")'
)
/*
{
// number of rows affected
changes: 1,
// SQL statement
stmt: <Statement>
}
*/
const result = await db.query(
'UPDATE tbl SET col = ? WHERE col = ?',
['new', 'old']
)
/*
{
// number of rows affected
changes: 1,
// SQL statement
stmt: <Statement>
}
*/
CATCH example
Catch execution exception
await db.query('INSERT INTO tbl VALUES ("test")')
.catch(error => { throw error });
await db.query('SELECT col FROM tbl WHERE col = ?', 'test')
.catch(e => {
console.error(e);
throw e
});