Sequelize 其实就是node.j和MySQL之间的一个桥梁,是用javascript写的object关系映射库。
1. 首先安装依赖:
npm install mysql
npm install sequelize
— Setting up the connection with mysql
2.连接MySQL
//Including dependency
var Sequelize = require("sequelize");
//Setting up the config
var sequelize = new Sequelize('your-database-name', 'db-username', 'db-password', {
host: "localhost",
port: 3306,
dialect: 'mysql'
});
检查连接的状态
sequelize.authenticate().complete(function (err) {
if (err) { console.log('There is connection in ERROR'); } else { console.log('Connection has been established successfully'); }
});
3.用node.js 创建一个表
//创建表的结构
var Item = sequelize.define('Item', {
id: Sequelize.STRING,
name:Sequelize.STRING,
description: Sequelize.STRING,
qty: Sequelize.INTEGER
});
//申请项目表数据库
sequelize.sync({force:true}).complete(function (err) {
if(err){
console.log('An error occur while creating table');
}else{
console.log('Item table created successfully');
}
});
1.插入操作
有两种方法,第一种:
var item1 = Item.build({
id: 1,
name:'Laptop',
description: 'Acer 2340TL',
qty: 23
});
//Inserting Data into database
item1.save().complete(function (err) {
if (err) {
console.log('Error in Inserting Record');
} else {
console.log('Data successfully inserted');
}
});
第二种
sequelize.sync().success(function () {
Item.create({
id: 2,
name:'Cell Phone',
description: 'Sony',
qty: 20
}).success(function (data) {
console.log(data.values)
})
});
2.从表中读取数据
//读取所有的数据
Item.find({}).complete(function (err,data) {
console.log(data);
});
//条件读取
Item.find({where:{name:'Laptop'}}).complete(function (err, data) {
console.log(data);
});
3.更新数据表
//更新Laptop 到 Computer
Item.find({where:{name:'Laptop'}}).complete(function (err, data) {
if(err){
console.log(err);
}
if(data){
data.updateAttributes({
name:'Computer'
}).success(function (data1) {
console.log(data1);
})
}
});
4.从表中删除数据
//删除所有名字为compter的数据
Item.find({where: {name: 'Computer'}}).complete(function (err, data) {
if (err) {
console.log(err);
} else {
data.destroy({}).success(function (err, data) {
if(err){
console.log(err);
}else{
console.log(data);
}
})
}
console.log(data);
});
你可以在 GITHUB上点击查看源代码,也可以查看sequelise官方文档