Created
March 24, 2016 04:56
-
-
Save rizafahmi/895dc35e5f9eabf098e5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 pg = require('pg') | |
var faker = require('Faker') // install using npm install Faker | |
var conString = "postgres://postgres:5432@localhost/students" | |
var client = new pg.Client(conString) | |
client.connect((err) => { | |
if(err) { | |
return console.error('could not connect to postgres', err) | |
} | |
// --------------------------------------- | |
// cleanup (if we've run this more than once) | |
// --------------------------------------- | |
client.query("DROP TABLE if EXISTS students;") | |
// --------------------------------------- | |
// create the table we'll use later | |
// --------------------------------------- | |
client.query("CREATE TABLE students ( lastname varchar(200), firstname varchar(200), cohort varchar(200), phase int);") | |
// --------------------------------------- | |
// INSERT | |
// --------------------------------------- | |
for (var i=0; i<11; i++) { | |
var firstName = faker.Name.firstName() | |
var lastName = faker.Name.lastName() | |
var company = faker.Company.bs() | |
var phase = Math.floor(Math.random() * 1000) | |
client.query(`INSERT INTO students (firstname, lastname, cohort, phase) VALUES ('${firstName}', '${lastName}', '${company}', ${phase})`) | |
} | |
// --------------------------------------- | |
// SELECT | |
// --------------------------------------- | |
client.query('SELECT * FROM students', (err, result) => { | |
if(err) { | |
return console.error('error running query', err) | |
} | |
console.log(result.rows) | |
}) | |
// --------------------------------------- | |
// UPDATE | |
// --------------------------------------- | |
client.query("UPDATE students SET firstname='Homer', lastname='Simpson' WHERE phase = 14") | |
client.query('SELECT * FROM students', (err, result) => { | |
if(err) { | |
return console.error('error running query', err) | |
} | |
console.log(result.rows) | |
}) | |
// --------------------------------------- | |
// DELETE | |
// --------------------------------------- | |
client.query("DELETE FROM students") | |
client.query('SELECT * FROM students', (err, result) => { | |
if(err) { | |
return console.error('error running query', err) | |
} | |
console.log(result.rows) | |
client.end() | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment