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.
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]
How to import an SQL file in MySQL
While working on web application, often...How to detect click inside iframe using JavaScript
Use the jQuery contents() method If y...Laravel 8 Authentication using Breeze Tutorial
Laravel team have created multiple authe...Change Password with Current Password Validation in Laravel
Today, we will learn to update password...How to Remove Duplicate Values from an Array in PHP
In this article, i will share with you h...