My problem is to figure out when to close a database connection from an expressjs backend to a sqlite database.
What I basically want to achieve is a database connection which is open during the whole server uptime and is closed on server shutdown.
var express = require('express')
var app = express()
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(data/Test.db);
//use db as needed
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
//on shutdown db.close();
I had a look at these threats:
Stack overflow: process.on('exit', callback)
Github issue: App has no app.close()
But the suggested solutions wouldn't work for me if I kill me express server with ctrl+c
.
So what would be a 'best practice' on how to handle an open database connection on server shutdown?
The sqlite3 module connect() ; the connection must be closed at the end of the session with the . close() command. While the connection is open, any interactions with the database require you to make a cursor object with the . cursor() command.
close( conn ) closes the SQLite connection by using the MATLAB® interface to SQLite. The SQLite connection object remains open until you close it using the close function. Always close this object when you finish using it.
The sqlite3 module also works with node-webkit if node-webkit contains a supported version of Node. js engine. (See below.) SQLite's SQLCipher extension is also supported.
SQLite is a C library that provides a lightweight disk-based database that doesn't require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage.
SIGINT
is the signal you're looking for; most terminals send a SIGINT
on Ctrl+C
.
You could try something like this -
process.on('SIGINT', () => {
db.close();
server.close();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With