Skip to content
Advertisement

Azure functions: Exception: TypeError: connection.query is not a function

I have a simple Azure function trying to get all data from a SQL table. The connection is successful and I can connect to the database, but whenever I run the get request, I end up with an error

Exception: TypeError: connection.query is not a function
Stack: TypeError: connection.query is not a function

This is the line throwing the error

connection.query(query, (err, results, fields) => {

this is my index.js azure get function

const express = require('express')
const bodyParser = require('body-parser')
let connection = require('../configs/dbConfig')
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

module.exports = async function (context, req, res) {
    const query = 'SELECT * FROM entrys'
    connection.query(query, (err, results, fields) => {
        if (err) {
            const response = { data: null, message: err.message, }
            res.send(response)
        }

        const pokemons = [...results]
        const response = {
            data: pokemons,
            message: 'All entrys successfully retrieved.',
        }
        res.send(response)
    })
}

Am using tedious as the connection driver. my dbconfig

let Connection = require('tedious').Connection;

let pool = {
    server: "localhost", // or "localhost"
    authentication: {
        type: "default",
        options: {
            userName: "sa",
            password: "root",
        }
    },
    options: {
        database: "testing",
        encrypt: false
    }
};

var connection = new Connection(pool);
connection.on('connect',function(err){
if(err){
console.log('Connection Failed');
throw err;
}
else{
console.log('Connected');
}
});
module.exports = connection

what am I doing wrong, thank you in advance

Advertisement

Answer

You should use Request to query.

In the official documentation, I did not see the usage of connection.query. It is not recommended that you use tedious when you are not very familiar with it. I have a sample code here, I hope it helps you.

You can download my Sample Code which use mssql package.

var express = require('express');
var router = express.Router();
let connection = require('../configs/dbConfig')
var Request = require('tedious').Request; 

/* GET users listing. */
router.get('/', function(req, res, next) {
  request = new Request("select 42, 'hello world'", function(err, rowCount) {
    if (err) {
      console.log(err);
    } else {
      console.log(rowCount + ' rows');
    }
  });

  request.on('row', function(columns) {
    columns.forEach(function(column) {
      console.log(column.value);
    });
  });

  connection.execSql(request);
  res.send('respond with a resource');
});

module.exports = router;

Test Result:

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement