如果不存在则创建新数据库

如果不存在则创建新数据库

本文介绍了Sequelize Js - 如果不存在则创建新数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using ( SequelizeJs + NodeJs + Mysql ) in my project
Whenever I start the project I want to check the database exists or not and then if it's not there I want to create a new one.
I tried this:

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!');
    }
});

我收到此错误:

I am getting this error:

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

推荐答案

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

use following command to create"CREATE DATABASE IF NOT EXISTS DBName;"

这篇关于Sequelize Js - 如果不存在则创建新数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 00:50