ToB企服应用市场:ToB评测及商务社交产业平台

标题: Sequelize的简单连接和使用 [打印本页]

作者: 泉缘泉    时间: 2023-8-8 21:16
标题: Sequelize的简单连接和使用
Sequelize是一个基于Node.js的ORM框架
特点:

基本使用:
  1. const Sequelize = require('sequelize');
  2. //方法一/单独传递参数
  3. // const sequelize = new Sequelize('数据库账号', '数据库名字', '数据库密码', {
  4. //     host: 'localhost',
  5. //     dialect: 'mysql'
  6. // });
  7. // 方法二:传递连接URI
  8. // const sequelize = new Sequelize('mysql://数据库账号:数据库密码@localhost:3306/数据库名字',{
  9. //     timestamps:false //指定不自动创建createdAt和 updatedAt字段
  10. // })
  11. // 连接池(生产环境)
  12. const sequelize = new Sequelize('数据库名字', '数据库账号', '数据库密码', {
  13.     host: 'localhost',
  14.     dialect: 'mysql', // 或者其他你使用的数据库类型,如'postgres'、'sqlite'等
  15.     pool: {
  16.         max: 5, // 最大连接数
  17.         min: 0, // 最小空闲连接数
  18.         acquire: 30000, // 获取连接的超时时间(毫秒)
  19.         idle: 10000 // 连接空闲的超时时间(毫秒)
  20.     }
  21. });
  22. //测试连接
  23. sequelize
  24.     .authenticate()
  25.     .then(() => {
  26.         console.log('Connection has been established successfully')
  27.     })
  28.     .catch(err => {
  29.         console.log('unable to connect to the database:', err)
  30.     })
  31. const Model = Sequelize.Model;
  32. class User extends Model {}
  33. User.init({
  34.     //attributes
  35.     firstName: {
  36.         type: Sequelize.STRING,
  37.         allowNull: false
  38.     },
  39.     lastName: {
  40.         type: Sequelize.STRING
  41.     }
  42. }, {
  43.     sequelize,
  44.     modelName: 'user',
  45.     timestamps: true  //true为创建createdAt和updatedAt字段
  46. })
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4