7

Node.js MySQL Create table into Database Server

 2 years ago
source link: https://www.laravelcode.com/post/node-js-mysql-create-table-into-database-server
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Node.js MySQL Create table into Database Server

  221 views

  7 months ago

NodeJS

This article will guide you to how to create table into MySQL database server from Node.js.

First create connection between MySQL server and Node.js.

After database created, use conn.query() method to run CREATE TABLE query into MySQL database.

var query = `CREATE TABLE visitors(
    id int NOT NULL,
    browser varchar(255) NOT NULL,
    percentage decimal(10,2) NOT NULL
)`; 

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

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

const mysql = require('mysql');

const conn = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    database: 'charts',
    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 TABLE visitors(
            id int NOT NULL,
            browser varchar(255) NOT NULL,
            percentage decimal(10,2) NOT NULL
        )`;
        // query to database
        conn.query(query, function(err, response) {
            if (err) {
                return console.log(err.message);
            } else {
                console.log('Database table 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_table.js

The application will response with console messages we have set.

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

In this article, we have created MySQL database table with Node.js. In the later article, we will insert data into  MySQL database table.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK