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]
Laravel 8 Listen Model Observers Tutorial Example
If you want to listen many events for an...JavaScript Check if String Contains a Substring
JavaScript has rich library of functions...Create custom error page in Laravel 8
Laravel provides with default all errors...Encrypt and Decrypt Data in NodeJS using Crypto
We will share with you in this article h...Laravel 8 Firebase Phone Number OTP Authentication Example
Firebase is a realtime cloud-hosted NoSQ...