【问题标题】:Sequelize Js - Create new database if its not existsSequelize Js - 如果不存在则创建新数据库
【发布时间】:2019-11-30 10:09:09
【问题描述】:

我在我的项目中使用(SequelizeJs + NodeJs + Mysql)
每当我启动项目时,我都想检查数据库是否存在,如果不存在,我想创建一个新的。
我试过这个:

const mysql        = require('mysql2');

let mysqlCon = mysql.createConnection({
    host    :config.host,
    user    :config.username,
    password:config.password
});

mysqlCon.connect(function(err) {

    //Check Database
    mysqlCon.query('SHOW DATABASES LIKE ' + config.database,
        function(err, result) {
            if(err) {

                //Create new Database
                mysqlCon.query(
                    'CREATE DATABASE ' + config.database,
                    function(err, result) {
                        if(!err){

                            //Sync sequelize js model files
                            models.sequelize.sync().then(() => {
                                console.log('Database connected successfully!');
                            }).catch((err) => {
                                console.log(err, 'Something went wrong with the Database!');
                            });

                        }
                    });
            }
        });
    if(err) {
        console.log(err.message);

    } else {
        console.log('Connected!');
    }
});

我收到此错误:

sqlMessage: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'pixljobs\' at line 1' } undefined

【问题讨论】:

标签: mysql node.js sequelize.js mysql2 node-mysql


【解决方案1】:

使用以下命令创建 "如果 DBName 不存在则创建数据库;"

【讨论】:

    【解决方案2】:

    也许,另一种方法是使用 Sequelize 迁移。

    在此处查看文档:https://sequelize.org/master/manual/migrations.html

    安装 sequelize-cli 后,初始化项目,添加迁移以初始化 DB 架构(表、索引等),然后运行命令 db:create,然后运行 ​​db:migrate

    一个迁移文件由两部分组成:“up”函数,是您应用到 DB 的函数,“down”函数,是您需要回滚的函数。 它看起来像这样:

    module.exports = {
      up: (queryInterface, Sequelize) => {
        // logic for transforming into the new state
      },
      down: (queryInterface, Sequelize) => {
        // logic for reverting the changes
      }
    }
    

    这种方法的优点是您可以以一种自动化、可扩展的方式初始化不同的环境。

    最后,要回答您的问题,您只需确保在要运行项目的每个环境中运行 sequelize-cli db:createsequelize-cli db:migrate,以确保数据库具有正确的架构。如果您使用的是 sequelize-cli > v5.2.0,db:create 将在 DB 不存在时创建它,如果它已经创建则将使用现有 DB(在幕后运行 Kumaresan 向您展示的命令)。

    希望这会有所帮助!

    【讨论】:

      【解决方案3】:

      2021 年,Sequelize 尚未为 mariadb 实现 db:create,如果您遇到同样的问题,我发现的解决方法是 osifo 的答案:https://stackoverflow.com/a/46694727/11940283

      在我的情况下,我刚刚创建了另一个名为 create-database.js 的文件,并在运行以下迁移之前使用 node create-database.js 运行此文件:create-node database.js && npx sequelize-cli db:migrate 但我认为更好的解决方案是将此代码放在第一次迁移中实际迁移代码之前的文件,然后正常运行迁移。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-13
        • 1970-01-01
        • 2020-12-07
        • 2012-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多