Thank you again for your help. I just begin using Node and SQLite (before this I do most of my work in PHP, MySQL).
Currently, I am just try to figure it out how to create a simple CRUD web. When I test SQLite, I just pack every query in the serialize as you said. Then, I try to make a module as follow:
var sqlite3 = require('sqlite3').verbose();
class dbContact {
constructor() {
this.db = new sqlite3.Database(':memory:');
}
async createContactTable() {
const {db} = this;
try {
db.serialize(() => {
db.run("CREATE TABLE IF NOT EXISTS tbl_contact(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone TEXT, photo TEXT)", (err)=>{console.log(`Hah? ${err}`)})
.each("select count(*) as exp from tbl_contact", (err, row) => {
if(err) throw err;
console.log(`No.: ${row.exp}`);
});
});
} catch(err) {
console.log(err);
}
}
async addContact(aContact) {
const {db} = this;
const sql = `INSERT INTO tbl_contact (name, phone, photo) VALUES ('${aContact[0]}', '${aContact[1]}', '${aContact[2]}')`;
db.run(sql, (err)=>{console.log(`Huh? SQL: ${sql} ${err}`)});
console.log(`add data`);
}
}
const dbc = new dbContact();
module.exports = dbc;
then I expected to use it some what like this:
const dbc = require('./db_engine_3');
dbc.createContactTable();
dbc.addContact(["Woravit", "xx-4149-xxxx","./images/a.png"]);
dbc.addContact(["Tazz", "xx-4694-xxxx","./images/b.png"]);
}
At first, when it doesnât work, I think that it is about the asynchronize nature of Node, so it try
const dbc = require('./db_engine_3');
async function prepareDatabase() {
const a = await dbc.createContactTable();
console.log(a);
await dbc.addContact(["Woravit", "08-4149-7009","./images/a.png"]);
await dbc.addContact(["Tassanee", "08-4694-4171","./images/b.png"]);
}
prepareDatabase();
which also doesnât work as you have explain above.
I am not sure but I think maybe when I really do it web based (e.g. request update, delete, etc. via browser instead of writing a whole test code in single js file) it will not has this problem.