如何使用 sequelize (nodejs) 创建 mysql 数据库

我正在尝试尽可能地自动化创建数据库和表的过程.是否可以通过 sequelize 创建数据库?我可以创建一个只连接到服务器而不是直接连接到 db 的连接字符串吗?

I am trying to automate the process of creating db and tables as much as possible. Is it possible to create database via sequelize? Can I make a connection string that connects just to server, not to db directly?

推荐答案

简答:当然可以!

我是这样完成的:

//create the sequelize instance, omitting the database-name arg
const sequelize = new Sequelize("", "<db_user>", "<db_password>", {
  dialect: "<dialect>"
});

return sequelize.query("CREATE DATABASE `<database_name>`;").then(data 
=> {
  // code to run after successful creation.
});

附:在哪里放置代码取决于您的需要.在初始迁移文件中对我有用.

P.S. Where to place code would depend on your need. Inside an initial migration file worked for me.

相关文章