官方文档的构造器很多,这里仅展示一种 const { Sequelize } = require('sequelize'); /** * dbname * username * password * options */ const sequelize = new Sequelize('dbname', 'username', 'password', { host: '127.0.0.1', //注意一定不要写成localhost,不然会连不上数据库,报最后附上的错误 dialect: 'mysql', port: 3306, //以下配置在dialectOptions中的参数会被加在连接地址后作为参数传给mysql等同于 //mysql://localhost:3306/dbname?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai //自己看着加参数,不加也行,也能连上mysql // dialectOptions: { // useSSL: false, // allowPublicKeyRetrieval: true, // serverTimezone: 'Asia/Shanghai', // useUnicode: true, // characterEncoding: 'UTF-8' // }, }); async function connect() { try { await sequelize.authenticate(); console.log('Connection has been established successfully.'); } catch (error) { console.error('Unable to connect to the database:', error); } } connect() ################################################## host写localhost会报的错,改成ipv4地址连接就行了
original: Error: connect ECONNREFUSED ::1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3306,
fatal: true
}