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.