Guest User

Untitled

a guest
Jan 6th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. var pg = require('pg');
  2. var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";
  3.  
  4. var client = new pg.Client(conString);
  5. client.connect();
  6.  
  7. //queries are queued and executed one after another once the connection becomes available
  8. var x = 1000;
  9.  
  10. while (x > 0) {
  11. client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
  12. client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]);
  13. x = x - 1;
  14. }
  15.  
  16. var query = client.query("SELECT * FROM junk");
  17. //fired after last row is emitted
  18.  
  19. query.on('row', function(row) {
  20. console.log(row);
  21. });
  22.  
  23. query.on('end', function() {
  24. client.end();
  25. });
  26.  
  27.  
  28.  
  29. //queries can be executed either via text/parameter values passed as individual arguments
  30. //or by passing an options object containing text, (optional) parameter values, and (optional) query name
  31. client.query({
  32. name: 'insert beatle',
  33. text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
  34. values: ['George', 70, new Date(1946, 02, 14)]
  35. });
  36.  
  37. //subsequent queries with the same name will be executed without re-parsing the query plan by postgres
  38. client.query({
  39. name: 'insert beatle',
  40. values: ['Paul', 63, new Date(1945, 04, 03)]
  41. });
  42. var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);
  43.  
  44. //can stream row results back 1 at a time
  45. query.on('row', function(row) {
  46. console.log(row);
  47. console.log("Beatle name: %s", row.name); //Beatle name: John
  48. console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
  49. console.log("Beatle height: %d' %d"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
  50. });
  51.  
  52. //fired after last row is emitted
  53. query.on('end', function() {
  54. client.end();
  55. });
Add Comment
Please, Sign In to add comment