1. 程式人生 > >【nodeJS】連線【MySql】資料庫

【nodeJS】連線【MySql】資料庫

準備資料庫:redmine 在這裡插入圖片描述 工程結構: 在這裡插入圖片描述 config .js

var config = {
    database: 'redmine', // 使用哪個資料庫
    username: 'redmine', // 使用者名稱
    password: '123456', // 口令
    host: 'localhost', // 主機名
    port: 3306 // 埠號,MySQL預設3306
};

module.exports = config;

app.js

'use strict';

const Sequelize = require('sequelize');
const config = require('./config');
const Op = Sequelize.Op;
var sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000,
        operatorsAliases: {
            $and: Op.and,
            $or: Op.or,
            $eq: Op.eq,
            $gt: Op.gt,
            $lt: Op.lt,
            $lte: Op.lte,
            $like: Op.like
          }
    }
});

var Pet = sequelize.define('pet', {
    id: {
        type: Sequelize.STRING(50),
        primaryKey: true
    },
    name: Sequelize.STRING(100),
    gender: Sequelize.BOOLEAN,
    birth: Sequelize.STRING(10),
    createdAt: Sequelize.BIGINT,
    updatedAt: Sequelize.BIGINT,
    version: Sequelize.BIGINT
}, {
        timestamps: false
    });

var now = Date.now();
Pet.create({
    id: 'g-' + now,
    name: 'Gaffey',
    gender: false,
    birth: '2007-07-07',
    createdAt: now,
    updatedAt: now,
    version: 0
}).then(function (p) {
    console.log('created.' + JSON.stringify(p));
}).catch(function (err) {
    console.log('failed: ' + err);
});

(async () => {
    var pets = await Pet.findAll({
        where: {
            name: 'Gaffey'
        }
    });
    console.log(`find ${pets.length} pets:`);
    for (let p of pets) {
        console.log(JSON.stringify(p));
    }
})()

除錯執行: 在這裡插入圖片描述 在這裡插入圖片描述