0

I want to know if node.js mysql gives a query success indicator. I want to do a CREATE DATABASE IF NOT EXIST query, and if the database did not exist and was created properly, execute a bunch of files (that create my tables). The files that create the tables are already coded and I tested them. I just do not understand (due to really meh documentaton) how to do "if database was successfully created do x else do y" portion of the logic.

const config = require("./database");

var connection = config.db.get;

connection.query(
    "CREATE DATABASE IF NOT EXISTS " . config.database,
    function (err, result, fields) {
        if (err) throw err;

        console.log("result: " + result);

        if(!success) {
            //do nothing, we assume the database adn tables are already setup.
        }
        else {
            require("./models/company");
            require("./models/locations");
        }
    });

How can I create a boolean variable based on if the query was successful or not, assuming that it would be false if the database exists before running the CREATE DATABASE query.

1 Answer 1

1

Your "IF NOT EXISTS" part suppresses the "error". So you could either:

  1. Just do a "CREATE DATABASE ABC" - this should throw an error. So you could do if (err) {...do something...}

  2. You could check beforehand if the database exists with something like this "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'ABC'"

Sign up to request clarification or add additional context in comments.

4 Comments

I will try this when I get home from work. Is the error a blank string if the query is successful?
I don't know for mysql. Usually it's null so "if (err === null) {...all good...}"
Ill try both and start to document how the module works on my website.
It is correct to say that if err is not null, the query did not return results.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.