Created
August 23, 2012 21:03
-
-
Save chilts/3441701 to your computer and use it in GitHub Desktop.
Example Node.js + Postgres tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fmt = require('fmt'); | |
var pg = require('pg'); | |
var conString = "pg://scroober@localhost/scroober"; | |
pg.connect(conString, function(err, cl) { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
// disconnect client when all queries are finished | |
cl.on('drain', cl.end.bind(cl)); | |
cl.query("SELECT NOW() as when", function(err, result) { | |
fmt.title('SELECT NOW()'); | |
console.log("Row count: %d",result.rows.length); // 1 | |
console.log("Current year: %d", result.rows[0].when.getYear()); | |
fmt.line(); | |
}); | |
cl.query("SELECT * FROM property", function(err, result) { | |
fmt.title('Property Table'); | |
console.log("Row count: %d", result.rows.length); // 1 | |
fmt.line(); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fmt = require('fmt'); | |
var pg = require('pg'); | |
var client = new pg.Client({ | |
user : 'scroober', | |
database : 'scroober', | |
}); | |
// disconnect client when all queries are finished | |
client.on('drain', client.end.bind(client)); | |
client.connect(function(err) { | |
fmt.line(); | |
fmt.title('Inside client.connect()'); | |
if (err) { | |
console.log(err); | |
return; | |
} | |
console.log('Connected'); | |
client.query("SELECT * FROM property", function(err, result) { | |
fmt.line(); | |
console.log("Row count : %d", result.rows.length); // 1 | |
fmt.dump(result, 'result'); | |
fmt.line(); | |
}); | |
// create a parameterized query | |
var query = client.query({ | |
text : 'SELECT key, value FROM property WHERE key = $1 OR key = $2', | |
values : ['Greeting', 'Theme'] | |
}); | |
query.on('row', function(row) { | |
fmt.title('New Row'); | |
fmt.dump(row, 'row'); | |
fmt.line(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment