node使用sequelize调用mysql

sequelize

安装依赖

npm install sequelize --save

创建文件夹

sequelize
    -> config.js
    -> modules
        -> user
            -> User.js
            -> BuiltInUser.js
        ...
    -> services
        User.js

sequelize/config.js

// 引⼊sequelize库
// Sequelize:类,DataTypes:数据类型,Op:运算符合辑
const { Sequelize } = require("sequelize"); // 引⼊sequelize
// 创建Sequelize实例
const sequelize = new Sequelize("mysqltest", "root", "123456", {
	host: "localhost",
	dialect: "mysql",
	port: 3306,
	logging: (sql) => {
		console.log(sql); // 将 SQL 查询⽇志打印到控制台
	},
	dialectOptions: {
		logQueryParameters: true, // 显示实际参数值
	},
	timezone: "+08:00", // 设置为中国的时区(北京时间,UTC+8)
});
sequelize
	.authenticate()
	.then(() => {
		console.log("sequelize数据库连接成功!");
	})
	.catch((err) => {
		console.error("数据库连接失败!", err);
	});
// 导出实例
module.exports = sequelize;

sequelize/modules/user/User.js

const { DataTypes } = require("sequelize");
const sequelize = require("../../config");
const BuiltInUser = require("./BuiltInUser");
const User = sequelize.define(
	"users",
	{
		id: {
			type: DataTypes.INTEGER,
			allowNull: false,
			primaryKey: true,
			autoIncrement: true,
		},
		// 定义数据模型的字段
		username: {
			type: DataTypes.STRING, // 字段类型为字符串
			allowNull: false, // 不允许为空
		},
		password: {
			type: DataTypes.STRING, // 字段类型为字符串
			allowNull: false, // 不允许为空
		},
		gender: {
			type: DataTypes.ENUM,
			values: ["0", "1", "2"], // 0: 男,1: 女,2: 保密
			defaultValue: "2", // 默认为保密
			allowNull: false, // 不允许为空
		},
		role: {
			type: DataTypes.ENUM, // 字段类型为整数
			values: ["1", "2"], // 1: 管理员,2: 普通用户
			defaultValue: "1", // 默认值为 1
			allowNull: false, // 不允许为空
		},
		description: {
			type: DataTypes.TEXT, // 字段类型为字符串
			allowNull: true, // 不允许为空
		},
		avatar: {
			type: DataTypes.STRING, // 字段类型为字符串
			allowNull: true, // 不允许为空
		},
	},
	{
		sequelize,
		// 告诉 sequelize 不需要自动将表名变成复数
		freezeTableName: true,
		modelName: "User",
		timestamps: true, // 自动创建 createdAt 和 updatedAt 字段
		createdAt: "createdAt",
		updatedAt: "updatedAt",
		paranoid: true, // 软删除,不物理删除数据 设置为true数据库会增加deletedAt
	}
);
User.sync({ force: true }).then((res) => {
	console.log("User 模型创建成功");
	BuiltInUser(User);
});
module.exports = User;

sequelize/modules/user/BuiltInUser.js

const USERS = [
	{
		username: "admin",
		password: "123456",
		gender: "1",
		role: "1",
		description: "this is a admin user",
		avatar: null,
	},
	{
		username: "test",
		password: "Aa123456",
		gender: "2",
		role: "2",
		description: "",
		avatar: "",
	},
];
const BuiltInUser = (User) => {
	User.bulkCreate(USERS, { individualHooks: true }); // 创建基础数据
};
module.exports = BuiltInUser;

sequelize/services/User.js

const User = require("../modules/user/User");

const UserService = {
	login: async ({ username, password }) => {
		return await User.findAll({
			where: {
				username,
				password,
			},
		});
	},
	getUserInfo: async (id) => {
		return await User.findByPk(id);
	},
	updateUserInfo: async (id, data) => {
		await User.update(data, {
			where: {
				id,
			},
		});
	},
	deleteUser: async (id) => {
		// 模型如果配置了 paranoid: true
		// 则 删除的时候会添加删除时间,即为软删除,而非真正的删除
		await User.destroy({
			where: {
				id,
			},
		});
	},
};

module.exports = UserService;
// findAll 查询所有匹配项
// findByPk 根据主键查询
/* 
  const project = await Project.findByPk(123);
*/
// findOne 查询单个匹配项
/* 
  const project = await Project.findOne({ where: { title: 'My Title' } });
*/
// findOrCreate 根据条件查找或创建
// findAndCountAll 查询所有匹配项并返回总数
/* 
  const { count, rows } = await Project.findAndCountAll({
    where: {
      title: {
        [Op.like]: 'foo%',
      },
    },
    offset: 10,
    limit: 2,
  });
  console.log(count);
  console.log(rows);
*/

// create 创建新记录
/* 
  const jane = await User.create({ name: 'Jane' });
  // Jane exists in the database now!
  console.log(jane instanceof User); // true
  console.log(jane.name); // "Jane"
*/
// build 创建新记录但不保存

contriller中使用

eg1. login中查询用户
    // 使用的是findAll,返回Array,读取每一项的,dataValues, 登录一般是第0条数据,只会返回0条或1条数据
    let result = await UserService.login(req.body);
    console.log(result);
eg2.根据id获取用户信息
    // 使用的是findByPk,返回Object,读取dataValues
    let user1 = await UserService.getUserInfo("1");
    console.log("user1: ", user1.dataValues);
eg3. 根据id修改用户信息,此处修改的是用户的简介
    // 使用的是update
    UserService.updateUserInfo("1", { description: "123" });
eg4. 根据id删除数据(用户)
    // 使用的是destroy
    UserService.deleteUser("2");

其他方法

findOne 查询单个匹配项
    const project = await Project.findOne({ where: { title: 'My Title' } });
findAndCountAll 查询所有匹配项并返回总数,分页查询用到
    const { count, rows } = await Project.findAndCountAll({
        where: {
          title: {
            [Op.like]: 'foo%',
          },
        },
        offset: 10,
        limit: 2,
    });
    console.log(count);
    console.log(rows);
create 创建新记录
    const jane = await User.create({ name: 'Jane' });
    // Jane exists in the database now!
    console.log(jane instanceof User); // true
    console.log(jane.name); // "Jane"
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值