koa+squelize连接数据库
Posted zx-666
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了koa+squelize连接数据库相关的知识,希望对你有一定的参考价值。
准备连接数据库:
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连接数据库的主要内容,如果未能解决你的问题,请参考以下文章
基于 Koa平台Node.js开发的KoaHub.js连接打印机的代码
mpvue+koa+mysql小程序开发,从数据库中取出的数据无法显示到页面上
typescript-koa-postgresql 实现一个简单的rest风格服务器 —— 连接 postgresql 数据库