http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001471955049232be7492e76f514d45a2180e2c224eb7a6000
mysql -u root -p
创建数据库
create database test;
show databases;
grant命令是创建MySQL的用户名和口令,均为www,并赋予操作test数据库的所有权限。
grant all privileges on test.* to 'www'@'%' identified by 'www';
use test;
创建表
create table pets (
id varchar(50) not null,
name varchar(100) not null,
gender bool not null,
birth varchar(10) not null,
createdAt bigint not null,
updatedAt bigint not null,
version bigint not null,
primary key (id)
) engine=innodb;
package.json
{
"name": "hello-sequelize",
"version": "1.0.0",
"description": "Hello Sequelize example with async",
"main": "app.js",
"scripts": {
"start": "node --use_strict app.js"
},
"keywords": [
"sequelize",
"async"
],
"author": "Michael Liao",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/michaelliao/learn-javascript.git"
},
"dependencies": {
"sequelize": "3.24.1",
"mysql": "2.11.1"
}
}
config.js
var config={
database:'test',
username:'www',
password:'www',
host:'localhost',
port:3306
};
module.exports=config;
app.js
const Sequelize = require('sequelize');
const config = require('./config');
var sequelize = new Sequelize(config.database, config.username, config.password, {
host: config.host,
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 300000
}
});
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 dog = await Pet.create({
id: 'd-' + now,
name: 'Odie',
gender: false,
birth: '2008-08-08',
createdAt: now,
updatedAt: now,
version: 0
});
console.log('created:' + JSON.stringify(dog));
})();
(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));
console.log('update pet...');
p.gender = true;
p.updatedAt = Date.now();
p.version++;
await p.save();
if (p.version === 3) {
await p.destroy();
console.log(`${p.name} was destroyed.`);
}
}
})();