0

enter image description here

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?

1
  • Which Sqlite package are you using? Also return await foo() is the same as return foo() in this case (if you had it in a try..catch then return await would have value). Commented Jan 10, 2021 at 21:46

1 Answer 1

1

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)
})()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.