什么是Sequelize
Sequelize是一个Node.js的ORM(对象关系映射)库,它提供了一种简洁而强大的方式来与关系型数据库进行交互。ORM库的作用是将数据库表格与对象之间进行映射,使开发者可以使用面向对象的方式来操作数据库,而不需要直接编写SQL查询语句。通过使用Sequelize,您可以更高效地管理和操作关系型数据库,提高开发效率,并且减少编写和维护原生SQL语句的工作量。
初始化项目
mkdir sequelize_learning
cd sequelize_learning
npm init
#安装Sequelize
npm i sequelize
# 安装pg数据库驱动程序
npm i pg pg-hstore
根目录下新建server.js
文件。
连接到数据库
要连接到数据库,必须创建一个 Sequelize 实例。
//创建一个Sequelize实例
const Sequelize = require("sequelize");
const sequelize = new Sequelize('database_name', 'username', 'password', {
host: 'localhost',
dialect: 'postgres',
//可选项,连接池参数
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
测试连接
你可以使用.authenticate()
函数测试连接是否正常:
//测试连接
async function testConnect(){
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
testConnect();
模型
模型定义
使用 sequelize.define:
const User = sequelize.define('User', {
// 在这里定义模型属性
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull 默认为 true
}
}, {
// 这是其他模型参数
});
以下是一些常用的其他模型参数:
timestamps:默认为true。如果设置为false,将不会自动添加createdAt和updatedAt字段到模型中。
tableName:指定模型对应的数据库表格的名称。如果未指定,则默认情况下将使用模型名称的复数形式作为表格名称。
具体参数可以参考官方文档
模型同步
通过调用一个异步函数(返回一个Promise)model.sync(options)
。通过此调用,Sequelize 将自动对数据库执行 SQL 查询。
User.sync()
- 如果表不存在,则创建该表(如果已经存在,则不执行任何操作)User.sync({ force: true })
- 将创建表,如果表已经存在,则将其首先删除User.sync({ alter: true })
- 这将检查数据库中表的当前状态(它具有哪些列,它们的数据类型等),然后在表中进行必要的更改以使其与模型匹配.
示例:
//测试连接
async function testConnect(){
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
testConnect();
server.js完整代码:
const Sequelize = require("sequelize");
//创建一个Sequelize实例
const sequelize = new Sequelize('testdb', 'postgres', 'wfgdpg212', {
host: 'localhost',
dialect: 'postgres',
//可选项,连接池参数
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000
}
});
//测试连接
async function testConnect(){
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
testConnect();
//定义模型
const User = sequelize.define('User', {
// 在这里定义模型属性
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING
// allowNull 默认为 true
}
}, {
// 这是其他模型参数
});
//模型同步
async function uploadModel() {
await User.sync({ force: true });
console.log("用户模型表刚刚(重新)创建!");
}
uploadModel();