1.10.9. fejezet, Adatbázis elérés

PostgreSQL

PostgreSQL modul telepítés

sudo npm install pg

A db-teszt.js tartalma legyen:

const pg = require('pg'); 
const connectionString = process.env.DATABASE_URL || 'postgres://user:password@localhost:5432/db';
const client = new pg.Client(connectionString); client.connect(); const query = client.query(
  'select id,name from systemuser');
query.on('row', (row) => { console.log(row); });
query.on('end', () => { client.end(); });

Futtatás

node db-teszt.js

Kapcsolódó hivatkozások

MySQL

MySQL modul telepítése

npm install mysql2 --save 

Connection pool:

var mysql = require('mysql2');
var pool;
module.exports = {
    getPool: function () {
        if (pool) return pool;
        pool = mysql.createPool({
            host     : 'localhost',
            user     : 'username',
            password : 'password',
            database : 'cars'
        });
        return pool;
    }
};

Használata:

app.get("/car", function (req, res) {
    const pool = db.getPool();
    pool.getConnection(function(err, con) {
        if (err) {
            res.writeHead(500, {'Content-Type': 'application/json; charset=utf-8'});
            res.end(JSON.stringify(err));
        }
        const sql = "select * from car";
        con.query(sql, function (err, result) {
            if (err) {
                res.writeHead(500, {'Content-Type': 'application/json; charset=utf-8'});
                res.end(JSON.stringify(err))
                return;
            }
            res.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
            res.end(JSON.stringify(result));
        });
    });
})

SQLite

MongoDB

import { MongoClient } from 'mongodb';
import { Timestamp } from 'bson';
 
const url = 'mongodb://127.0.0.1:27017/';
const dbName = 'Temperatures';
 
MongoClient.connect(url).then((client: MongoClient) => {
    const db = client.db(dbName);
 
    const collection = db.collection(dbName);
 
    const recordedAt = new Date();
 
    const data = {
        recordedAt: recordedAt,
        temperature: 28,
        humidity: 44,
        offset: recordedAt.getTimezoneOffset()
    };
 
    collection.insertOne(data).then((result) => {
        client.close();
    }).catch((err) => {
        client.close();
        console.error(err);
    });
});