关于sequelize的准备工作这里不再赘述.
一、引入sequelize模块
- var Sequelize = require('sequelize');
二、连接数据库
- var sequelize = new Sequelize(
- 'sample', // 数据库名
- 'root', // 用户名
- 'psw', // 用户密码
- {
- 'dialect': 'mysql', // 数据库使用mysql
- 'host': 'localhost', // 数据库服务器ip
- 'port': 3306, // 数据库服务器端口
- 'define': {
- // 字段以下划线(_)来分割(默认是驼峰命名风格)
- 'underscored': true
- }
- }
- );
三、定义表
- var User = sequelize.define(
- 'user',
- {
- userId: {
- field: 'user_id',
- primaryKey: true,
- type: Sequelize.BIGINT,
- allowNull: false
- },
- userName: {
- field: 'user_name',
- type: Sequelize.STRING,
- allowNull: false
- },
- userIcon: {
- field: 'user_icon',
- type: Sequelize.STRING,
- allowNull: true
- },
- title: {
- field: 'title',
- type: Sequelize.STRING,
- allowNull: true
- },
- gender: {
- field: 'gender',
- type: Sequelize.ENUM('MALE','FEMALE'),
- allowNull: true
- },
- birth: {
- field: 'birth',
- type: Sequelize.STRING,
- allowNull: true
- },
- mail: {
- field: 'mail',
- type: Sequelize.STRING,
- allowNull: true
- },
- tel: {
- field: 'tel',
- type: Sequelize.STRING,
- allowNull: true
- },
- mobile: {
- field: 'mobile',
- type: Sequelize.STRING,
- allowNull: true
- },
- updateTime: {
- field: 'update_time',
- type: Sequelize.STRING,
- allowNull: true
- }
- },
- {
- tableName: 'user',
- timestamps: false,
- freezeTableName: true
- }
- );
四、往表里添加数据
- User.create({
- userId: 23,
- userName: '老杨',
- updateTime: '2016-01-22 18:37:22'
- });
五、修改表内数据
- var pram={'userName':'晓博'};
- user.update(
- pram,{
- 'where':{'userId':{eq:23}}
- }
- );//将userId等于23的userName改为'晓博'
六、删除表内数据
- user.destroy({'where':{'id':{eq:23}}});//将表内userId等于23的元组删除