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

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));
        });
    });
})