Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Js - Create new database if its not exists

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
like image 393
Suresh Pattu Avatar asked Mar 04 '23 17:03

Suresh Pattu


1 Answers

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

like image 65
Kumaresan Avatar answered Mar 06 '23 19:03

Kumaresan