What other actions can be performed with db.run()?


#1

Question

What other actions can be performed with db.run()?

Answer

As we may remember from this lesson, the run method from SQLite3, is in charge of all the queries that do not need a returned result. We see we can create tables, but we can see that we can also insert items in those tables:

  db.run(`INSERT INTO cities (name) VALUES ('New York')`, function(err) {
    if (err) {
      return console.log(err.message);
    }
    // get the last insert id
    console.log(`A row has been inserted with rowid ${this.lastID}`);
  }); 

and we can also update and delete items from tables with db.run()

db.run(`UPDATE cties SET name = ? WHERE name = ?`,['Gotham', 'New York'], function(err) {
  if (err) {
    return console.error(err.message);
  }
  console.log(`Row(s) updated: ${this.changes}`);
 
});

//delete

db.run(`DELETE FROM cities WHERE id=?`, 1, function(err) {
  if (err) {
    return console.error(err.message);
  }
  console.log(`Row(s) deleted ${this.changes}`);
});

Side note: if you pass three arguments to db.run(), the first one will be the query, the second one will be data values (that will substitute ?s) , and the third is the callback

When it is about manipulating the data in the database table, the best method is db.run() since it is an action-driven method.