Home编程语言NODE.JSnode利用sequelize连接mysql

node利用sequelize连接mysql

简述:

工作中用node开发一个后台管理系统,选用express (4.16.0)框架,本文描述的是链接mysql的实现!


1,安装sequelize

// Using NPM
$ npm install --save sequelize
$ npm install --save mysql2

2,code

const Sequelize = require('sequelize');

//Setting up a connection
const sequelize = new Sequelize('database','username','pwd',{
    host:'localhost',
    port:3306,
    dialect:'mysql',
});


//Test the connection
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


//create model
//Models are defined with sequelize.define('name', {attributes}, {options}).
const User = sequelize.define('table_name',{
  name:{
   type: Sequelize.STRING   //type 需要的表字段
  },
  channel: {
    type: Sequelize.INTEGER   //channel需要的表字段
  },
},
{
    freezeTableName: true,  // 默认false修改表名为复数,true不修改表名,与数据库表名同步
    timestamps: false       //闭Sequelize的自动添加timestamp的功能
}
);


//query
User.findAll().then(user => {
  console.log(user)
})

//return sequelize;
标注:

注意 freezeTableName: true 参数, 默认是false,会修改表名为复数,导致表找不到问题


参考资料:http://docs.sequelizejs.com/

打赏

1 thought on “node利用sequelize连接mysql

发表评论

电子邮件地址不会被公开。