马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
Sequelize是一个基于Node.js的ORM框架
特点:
基本使用:
- const Sequelize = require('sequelize');
- //方法一/单独传递参数
- // const sequelize = new Sequelize('数据库账号', '数据库名字', '数据库密码', {
- // host: 'localhost',
- // dialect: 'mysql'
- // });
- // 方法二:传递连接URI
- // const sequelize = new Sequelize('mysql://数据库账号:数据库密码@localhost:3306/数据库名字',{
- // timestamps:false //指定不自动创建createdAt和 updatedAt字段
- // })
- // 连接池(生产环境)
- const sequelize = new Sequelize('数据库名字', '数据库账号', '数据库密码', {
- host: 'localhost',
- dialect: 'mysql', // 或者其他你使用的数据库类型,如'postgres'、'sqlite'等
- pool: {
- max: 5, // 最大连接数
- min: 0, // 最小空闲连接数
- acquire: 30000, // 获取连接的超时时间(毫秒)
- idle: 10000 // 连接空闲的超时时间(毫秒)
- }
- });
- //测试连接
- sequelize
- .authenticate()
- .then(() => {
- console.log('Connection has been established successfully')
- })
- .catch(err => {
- console.log('unable to connect to the database:', err)
- })
- const Model = Sequelize.Model;
- class User extends Model {}
- User.init({
- //attributes
- firstName: {
- type: Sequelize.STRING,
- allowNull: false
- },
- lastName: {
- type: Sequelize.STRING
- }
- }, {
- sequelize,
- modelName: 'user',
- timestamps: true //true为创建createdAt和updatedAt字段
- })
复制代码 |