node.js - db sample

サンプルコード

let express = require('express');
let router = express.Router();
let http = require('https')
let parseString = require('xml2js').parseString
let mysql = require('mysql')

/* GET home page. */
router.get('/', function (req, res, next) {

    let cnn = mysql.createConnection({
        host:'localhost',
        user:'xxxxx',
        password:'xxxxx',
        database:'my-nodeapp-db',
        port: 8889
    })

    cnn.connect();

    cnn.query('select * from mydata', (error, results, fields) => {
        if (error == null) {
            let data = {title:'mysql',content:results};
            res.render("hello", data);
        } else {
            let data = { title: 'mysql-error', content: '' };
            res.render("hello", data);
        }
    });

    cnn.end();
});

module.exports = router;
Knex.js参考

knexjs.org

var knex = require('knex')({
    client: 'mysql',
    connection: {
        host: '127.0.0.1',
        user: 'xxxx',
        password: 'xxxx',
        database: 'my-nodeapp-db',
        port: 8889
    }
});

knex.select().from("mydata").then(rows => {
    console.log(rows)
});

sairoutine.hatenablog.com

Bookshelf参考

bookshelfjs.org