If we have a db.sqlite file already in the directory, do we need to create a new database file?

Question

If we have a db.sqlite file already in the directory, do we need to create a new database file?

Answer

No, we do not. If we had a db.sqlite file already existing, it will use it as the database for our project. we could also use other files if we had them, something like: animals.db or students.sqlite, this files would be recognized by the Database object as a database that we can use.

The same way, creating the new instance of a Database:

let  db = new sqlite3.Database('./db.sqlite');

will not just declare the database, but also open the connection to it.

A curious fact of the Database object is that it has two optional parameters: the type of open connection, and a callback function.

The function simply helps in case of an error which is the parameter it can receive, so if there is a problem on the connection, the error object passed to the callback will be returned, otherwise, we will just get null:

let db = new sqlite3.Database('./db.sqlite', err => {
  if (err){
    console.log(err);
  } else {
    console.log('Success');
});

Here we see that if it all goes well, we will see a string "Success" appearing in our browser’s console. The other parameter is an object that contains data which restricts how the database will operate, the values available are:

  1. sqlite3.OPEN_READONLY : open the database for read-only queries.
  2. sqlite3.OPEN_READWRITE : open the database for reading and writing queries.
  3. sqlite3.OPEN_CREATE : open the database, if the database does not exist, create a new database.

By default, it uses the OPEN_READWRITE | OPEN_CREATE mode, which means that if the database does not exist, the new database will be created and is ready to read and write data.

An example of a read-only database would be:

let db = new sqlite3.Database('./db.sqlite', sqlite3.OPEN_READONLY, err => {
  if (err){
    console.log(err);
  } else {
    console.log('Success');
});

Now that we know more about the Database instance and that we do not have to forcefully create a new database every time, we are ready to retrieve our first value from the database using Node-SQLite!!!

3 Likes

In this lesson we are using SQLite (for reasons explained above) using the export module “sqlite3”. If we were to use another database model, such as MySQL, PostgreSQL or MS SQL Server, do these database models have modules that we can export for use in JavaScript? Where can I find information about these modules?