Last active
May 30, 2021 02:12
-
-
Save fabrizzio-gz/8c80a4ea02d935a59a86f3175a9d7034 to your computer and use it in GitHub Desktop.
Postgres & Node.js using node-postgres tutorial src: https://onestepcode.com/postgres-nodejs-tutorial/
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
| -- Setting up database | |
| -- sudo -u posrgres | |
| CREATE USER my_user WITH PASSWORD '12356'; | |
| CREATE DATABASE db WITH OWNER='my_user'; | |
| -- sudo -u my_user psql db | |
| CREATE TABLE my_table( | |
| id int, | |
| name text, | |
| age int | |
| ); | |
| INSERT INTO my_table(id, name, age) VALUES | |
| (1, 'foo', 25), | |
| (2, 'bar', 30), | |
| (3, 'john', 45); |
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
| const { Pool } = require("pg"); | |
| const pool = new Pool({ | |
| user: "my_user", | |
| password: "123456", | |
| database: "db", | |
| host: "localhost", | |
| port: 5432, | |
| }); | |
| const insert = async () => { | |
| try { | |
| await pool.query("INSERT INTO my_table VALUES (4, 'Nick', 50)"); | |
| console.log("success"); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| }; | |
| const insertParam = async (id, name, age) => { | |
| try { | |
| await pool.query("INSERT INTO my_table VALUES ($1, $2, $3)", [ | |
| id, | |
| name, | |
| age, | |
| ]); | |
| console.log("success"); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| }; | |
| // DO NOT USE | |
| const insertUnsafe = async (id, name, age) => { | |
| try { | |
| await pool.query(`INSERT INTO my_table VALUES (${id}, ${name}, ${age})`); | |
| console.log("success"); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| }; | |
| const getRow = async (id) => { | |
| try { | |
| const res = await pool.query("SELECT * FROM my_table WHERE id=$1", [id]); | |
| console.log(res.rows[0]); | |
| } catch (err) { | |
| console.error(err); | |
| } | |
| }; | |
| // Terminate connection | |
| // pool.end(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment