Skip to content

Instantly share code, notes, and snippets.

@fabrizzio-gz
Last active May 30, 2021
Embed
What would you like to do?
Postgres & Node.js using node-postgres tutorial src: https://onestepcode.com/postgres-nodejs-tutorial/
-- 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);
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