Once you know how to connect to MySQL, its time to create your own database and tables in which you can persist application data.
Creating Database
In MySQL, a database is created using create database command followed by the name of database. For creating a database from a node application, you need to execute the same query.
A database query can be executed by calling query method on the object returned by the createConnection method that you learnt in the previous section. Example,

// import mysql module
const mysql = require('mysql');
// create connection object
const connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'root'
});

// connect to MySQL
connection.connect(function(err){
    if(err){
        console.log('Unable to connect', err);
    } else {
        // connection successful
        console.log('Connected!!!');
        // execute query
        connection.query('Create database node', function(err){
            if(err) {
                console.log(err);
            } else {
                console.log('Database created');
            }
        })
    }
});

query method takes at least one argument which is the SQL query to be executed.
You would like to know whether the query was successfully executed or not. If not, then what was the failure reason, supply a callback function as the second argument.
This callback function will receive the error object containing failure reason. For example, if you try to execute the above code twice, then second time it should give an error since the database already exists. Following is the error reason printed.

E:\node>node firstprogram.js
Connected!!!
{ Error: ER_DB_CREATE_EXISTS: Can’t create database ‘node’; database exists
at Query.Sequence._packetToError (E:\node\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)

If the query is successfully executed then the error object will be null.

Leave a Reply