cretz/node-tds — Issue #10: re-executing statement from a loop
Author: noregrets
Created: 2012-01-19 14:36:30+00:00
State: open

First of all, great work on this module.

I have a handful of items I need to loop through and query the db for information about each item. My code works fine if I only query the db once, but as soon as I query in a loop, I get an error stating that the client must be in the initial state before connecting. I assume I need to end the statement or connection after each query, but I'm not sure how to do that correctly. I tried numerous approaches for closing the connection with the same end result.

Here is my function that queries the db:

function queryMSSQL(callback) {
var length = '';
conn.connect(function(error) {
if (error != null) {
console.error('Received error while connecting to local db', error);
} else {
var stmt = conn.createStatement("SELECT cast(length as char) from mytable where filename = '123456'");
stmt.on('row', function(row) {
//console.log('Received row: ', row.getValue(0));
length = row.getValue(0);
});
stmt.on('done', function(done) {
conn.end();
});
stmt.execute();
}
})
.on('end', function() {
console.log('connection ended');
callback(length);
});
}

Here is how I call the function inside a loop. I will pass it more params when I'm done testing - right now I just execute the same static query for testing purposes:

queryMSSQL(function(returnValue) {
console.log('length: ' + returnValue);
});

I would greatly appreciate any advice to point me in the right direction.