Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
var sql = require('node-sqlserver-unofficial');
var Promise = require('promise');
var connectStr = "Driver={SQL Server Native Client 11.0};Server=localhost;Database=AdventureWorksDW2012;Trusted_Connection=yes";
var testData = [
{id: 1, foo: 'asdf'},
{id: 2, foo: 'zxcv'},
{id: 3, foo: 'qwer'},
{id: 4, foo: 'skdjflgsljd'}
];
sql.open(connectStr, function(err, conn) {
var
query = Promise.denodeify(conn.query.bind(conn)),
queryRaw = Promise.denodeify(conn.queryRaw.bind(conn)),
createTable = function(result) {
console.log('creating table');
return query('create table NodeTest (a int primary key, b varchar(50))');
},
addRows = function(result) {
var promise = Promise.resolve(true);
testData.forEach(function(item) {
promise = promise.then(function() {
console.log('inserting item');
return queryRaw('insert into NodeTest (a,b) values(?, ?)', [item.id, item.foo]) });
});
return promise;
};
if (err) {
console.log('error ' + err);
return;
}
query('drop table NodeTest')
.then(createTable, createTable) // drop table could fail because it doesn't exist first time so keep going
.then(addRows)
.then(function(result) { return query('select * from NodeTest') })
.then(function(result) {
console.log('got to end, result length: ' + result.length);
result.forEach(function(item) {
console.log(item.a + ' ' + item.b);
});
})
.catch(function(err) {
console.log(err);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment