Reputation: 36367
I'm working with node and sqlite using the sqlite3 npm package. I'm trying to run the following query in node:
SELECT PropertyId FROM 'myData' WHERE Code IS NULL LIMIT 5
You can see that this works manually in the screenshot. In node I have
async function select_Rs_from_table(db,tablename, limit) {
// SELECT PropertyId FROM 'myData' WHERE Code IS NULL;
let out
try {
const sql = `SELECT PropertyId FROM '${tablename}' WHERE Code IS NULL LIMIT ${limit}`;
console.log(sql);
out = await db.run(sql);
} catch (error) {
console.log(error);
}
return out;
}
When I run this with
const sqlite3 = require('sqlite3').verbose();
// open the database
const db = new sqlite3.Database('./test.db',
sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the database.');
});
console.log('here');
select_Rs_from_table(db, 'myData', 5).then(x => console.log(x));
I see:
Debugger attached.
SELECT PropertyId FROM 'myData' WHERE StateCode IS NULL LIMIT 5
Database {}
Connected to the database.
Waiting for the debugger to disconnect...
Where is the result? How to I access the expected output?
Upvotes: 0
Views: 394
Reputation: 7787
There are a couple issues: you're using Promise-based calls with the sqlite3
package, but that package uses callbacks. You're also using db.run
rather than db.get
for a select statement. To use Promises (async/await) you need the sqlite
package using sqlite3.Database
as a driver. Please try this fixed example:
const sqlite3 = require('sqlite3').verbose()
const sqlite = require('sqlite')
;(async () => {
const db = await sqlite.open({
filename: './test.db',
driver: sqlite3.Database
})
console.log('connected!')
async function select_Rs_from_table(tablename, limit) {
try {
const sql = `SELECT PropertyId FROM '${tablename}' WHERE Code IS NULL LIMIT ${limit}`
return await db.get(sql)
} catch (error) {
console.error(error)
}
}
select_Rs_from_table('myData', 5).then(console.log)
})()
Upvotes: 1