const Sequelize = require('sequelize');
const sequelize = new Sequelize('test','root','123',{
host:'localhost',
dialect:'mysql',
dialectOptions: {
socketPath: '/tmp/mysql.sock' // 指定套接字文件路径
}
});
// 测试连接
sequelize.authenticate().then(()=>{
console.log('Connection has been established successfully.');
}).catch(err=>{
console.log('Unable to connect to the database:',err);
});
// 定义模型
const User = sequelize.define('user',{
id:{
type:Sequelize.NUMBER,
primaryKey:true
},
name:{
type: Sequelize.STRING
}
},{
tableName:'user',
timestamps: false
})
// 查询
User.findAll().then(users=>{
console.log('All users:',JSON.stringify(users,null,4));
})
// 新增
// User.create({id:4,name:'john'}).then(res=>{
// console.log('name:',res.name)
// })
// 删除
// User.destroy({
// where:{
// id:4
// }
// }).then(()=>{
// console.log('Done');
// })
// 更新
// User.update({name:'张三丰'},{
// where: {
// id:3
// }
// }).then(()=>{
// console.log('Done')
// })