Thanks to @siggemannen I was able to solve the problem. Seeing the error made me think about whether a connection was assigned and I inspected other people's code and realized that when creating a PreparedStatement
I needed to pass in the ConnectionPool
object from mssql
's connect
function.
So I made these changes.
// db.js
var pool;
sql.connect(dbConfig).then(result => result = pool).catch(err => {
console.error("Connection issue: " + err)
console.error(err.stack)
})
module.exports = { pool, ...}
Then in the file where I needed to use the PreparedStatement
const { pool } = require("db");
// ... code
router.get('/debtors/', async (req, res) => {
const column = req.query.column
const ps = new sql.PreparedStatement(pool) // <--- This is the important part
ps.input('param', sql.VarChar(200))
ps.prepare('select * from debtor WHERE first = @param', err => {
console.log("ps.prepare err: " + err)
ps.execute({ param: column }, (err, result) => {
console.log("ps.execute: " + err);
res.send(result.recordset);
ps.unprepare(err => {
})
})
})
})
The problem was that since I assumed that the callback activated it meant that there was no error. Turns out the callback activates regardless of whether there is an error or not, and to check if there is an error. I need to check if err !== undefined
if it isn't undefined
then there's an error message in there.