Create database into MySQL Database Server from Node.js

In the previous article, we have seen how to connect Mysql database with Node.js. In this article, we will see how to query MySQL database server and create table.

After database created, use conn.query() method along with MySQL query parameter to run query into MySQL database.

After the query executed, close the connection using conn.end() method.

Below we have created create_database.js file with full example.

const mysql = require('mysql');

const conn = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'root',
});

conn.connect((err) => {
    if (err) {
        // throw err;
        return console.log(err.message);
    } else {
        // connection established
        console.log('Connected with mysql database.');
        // query
        var query = 'CREATE DATABASE charts';
        // query to database
        conn.query(query, function(err, response) {
            if (err) {
                return console.log(err.message);
            } else {
                console.log('Database created.');
            }
        });
    }
    // close the connection
    conn.end(function(err) {
        if (err) {
            // throw err;
            return console.log(err.message);
        } else {
              console.log('Connection with mysql closed.');
        }
    });
});

Now run the file into Node server.

node create_database.js

The application will response with console messages we have set.

Connected with mysql database.
Database created.
Connection with mysql closed.

So far in this article, we have created MySQL database with Node.js. In the later articles, we will use more query to MySQL database from Node.js.

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment