码迷,mamicode.com
首页 > 数据库 > 详细

koa+squelize连接数据库

时间:2020-07-04 18:50:05      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:pass   catch   option   default   class   dial   连接数据库   timezone   nec   

准备连接数据库:

const Sequelize = require("sequelize");
const {dbName,host,user,password,port} = require("./config/index").database;
const sequelize = new Sequelize(dbName,user,password,{
dialect:"mysql",
port,
host,
logging:console.log,
timezone:"+08:00"
});
sequelize.authenticate().then(()=>{
console.log("数据库连接成功");
}).catch(()=>{
console.log(‘数据库连接失败‘)
})
module.exports=sequelize;

建立模型:

1.使用sequelize.define:

const { Sequelize, DataTypes } = require(‘sequelize‘);

const sequelize = new Sequelize(‘sqlite::memory:‘);

const User = sequelize.define(‘User‘, {

// Model attributes are defined here

firstName: { type: DataTypes.STRING, allowNull: false }, l

astName: { type: DataTypes.STRING // allowNull defaults to true } },

{ // Other model options go here });

2.使用model:

const { Sequelize, DataTypes, Model } = require(‘sequelize‘);

const sequelize = new Sequelize(‘sqlite::memory‘);

class User extends Model {}

User.init({ // Model attributes are defined here

firstName: { type: DataTypes.STRING, allowNull: false },

lastName: { type: DataTypes.STRING // allowNull defaults to true } },

{ // Other model options go here

sequelize, // We need to pass the connection instance

modelName: ‘User‘ // We need to choose the model name });

koa+squelize连接数据库

标签:pass   catch   option   default   class   dial   连接数据库   timezone   nec   

原文地址:https://www.cnblogs.com/zx-666/p/13235770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!