跳到主要内容

连接服务器

信息

本文参考连接:长乐未央

本地安装mysql数据库

我之前用的是dockerdesktop版本发现并不是很好用啊,对我这种英文跟shit一样的人来讲,是折磨,吐槽一下哈,个人看法。这里我换成了国产的小皮面板。非常好用的,安装到使用,有手就行哈家人们,杠杠的!

安装Sequelize

本地安装好mysql之后,创建一个新的数据库,名字和用户随意,但是用户不能是root

这里数据库面板我使用的是Navicat 16小伙伴们用其他的也都可以的,如果需要可以联系我,免费提供破解版噢~🤭

项目根目录依次运行

npm install sequelize -S
npm install mysql2 -S
npm install sequelize-cli -g
sequelize init

运行完成之后会发现项目中多出了几个文件夹和文件

.
├── config
│ └── config.json
├── migrations
├── models
│ └── index.js
└── seeders

  • config 是配置的意思,这里放的也就是 sequelize 所需要的连接数据库的配置文件。
  • migrations 是迁移的意思,如果你需要对数据库做新增表、修改字段、删除表等等操作,就需要在这里添加 迁移文件 了
  • models 里面存放的是模型文件,我们使用 sequelize 来执行 CRUD,也就是 创建、读取、更新、删除数据,就需要用这里的模型了。每个模型都对应数据库中的一张表。
  • seeders,是存放的种子文件。一般会将一些需要添加到数据表的测试数据存在这里。只需要运行一个命令,数据表中就会自动填充进测试内容了。

配置config

我们需要在config文件夹中的config.json文件中配置连接数据库所需要的信息

例如:

config.json
{
"development": {
"username": "admin",
"password": "123456",
"database": "development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}

以上分别对应着开发环境、测试环境和生产环境数据库的配置,按需求改即可。 接下来,我们把原有的models文件夹下的index.js文件内容修改一下,将sequelize改为连接池连接

最开始的代码我忘了是啥样了,我直接把内容贴出来做一个高亮吧

/models/index.js
'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], {
...config, pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
} else {
sequelize = new Sequelize(config.database, config.username, config.password, {
...config, pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
}
(async () => {
try {
// 改为连接池连接
await sequelize.authenticate();
console.log('Connection has been established successfully.');
// 这里是每次模型更新都会更新到数据库,线上慎重~!!!!
await sequelize.sync({ alter: true });
} catch (error) {
console.error('Unable to connect to the database:', error);
}
})();

fs
.readdirSync(__dirname)
.filter(file => {
return (
file.indexOf('.') !== 0 &&
file !== basename &&
file.slice(-3) === '.js' &&
file.indexOf('.test.js') === -1
);
})
.forEach(file => {
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
db[model.name] = model;
});

Object.keys(db).forEach(modelName => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;