安装依赖
npm i egg-mysql --save // or yarn add egg-mysql --save
配置模块
config/plugins.ts
import { EggPlugin } from 'egg';
const plugin: EggPlugin = {
mysql: {
enable: true,
package: 'egg-mysql',
}
};
export default plugin;
配置数据库连接
config/config.${env}.ts
以local为例子 config/config.local.ts
...
exports.mysql = {
// 单数据库信息配置
client: {
// 域名
host: '127.0.0.1',
// 端口号
port: '3306',
// 用户名
user: 'root',
// 密码
password: '123456',
//数据库名
database: 'xxxx'
},
// 是否加载到 app 上,默认开启
app: true,
// 是否加载到 agent 上,默认关闭
agent: false,
};
...
plugins.ts 与 config.${env}.ts 两个文件的配置不要搞混了 确认无误后输入
npm run dev // or yarn dev
问题收集与解决
npm run dev 这个时候一般会报错(这里卡了我几天时间 ):
或者app中找不到mysql
网上搜一堆,总结了以下两个方法,必行:
- 由于Egg.js没有对ts版本的egg-mysql进行声明,所以需要在typing/index.d.ts文件中对Application接口写入合并
typings/index.d.ts
import 'egg';
import { Application } from 'egg';
declare module 'egg' {
interface Application {
mysql: any;
}
}
2.mysql版本导致的密码规则(mysql5不存在这个问题) mysql 8.0.4 以上版本安装时默认了caching_sha2_pasword的认证方式, 只需更改密码插件为 mysql_native_password
use mysql;
alter user 'root'@'localhost' identified with mysql_native_password by '你的密码';
flush privileges;
若还不行,使用navicat或者sequel pro检查一下是否能够正常连接你的数据库,连接信息是否正确