I am studying SQLite for Node.js. Currently I am at the very beginning. I tried to insert row to a table but got error. The code I am using comes from this tutorial.
This is the code:
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./database/sq-lite-data-base.db', (err) => {
if(err) {
return console.log(err.message);
}
console.log("Connected to database!")
});
// Create table named 'users' with two columns: 1 - 'name' which values to be of type "text",
// and "age" of type "integer"
// db.run('CREATE TABLE users(name text, age integer)'); //When this line is not connected I get different error: "The table users already exists"
// Insert two rows to table "users"
db.run('INSERT INTO users(name, age) VALUES("Riko", 29)', ['C'], (err) => {
if(err) {
return console.log(err.message);
}
console.log('Row was added to the table: ${this.lastID}');
})
The error I get is:
SQLITE_ERROR: no such table: users
Another thing that puzzles me is the second parameter of the function db.run
. In my case I have passed the argument ['C']
. But what does this argument do, or what is it designated for?
First you have to check the user
table in your db '/database/sq-lite-data-base.db'.
If not:
db.run('CREATE TABLE users(name TEXT,age INT)');
And you have to change the code in above snippet like this (note that it's important to use an old-school function () { ... }
style callback rather than an arrow function, otherwise this.lastID
will be undefined
, source: official docs):
db.run('INSERT INTO users(name, age) VALUES(?, ?)', ['Raiko',29], function (err) {
if(err) {
return console.log(err.message);
}
console.log('Row was added to the table: ${this.lastID}');
})
You can also refer about sqlite tutorial.http://www.sqlitetutorial.net/sqlite-nodejs/insert/