EN
Node.js - MySQL Create table
0 points
In this article, we would like to show you how to create a table in Node.js.
xxxxxxxxxx
1
const mysql = require('mysql');
2
3
const connection = mysql.createConnection({ // gets connection with database
4
host: 'localhost', // '127.0.0.1'
5
user: 'root',
6
password: 'password',
7
database: 'database_name',
8
});
9
10
connection.connect((error) => {
11
if (error) throw error;
12
const query = `CREATE TABLE users (
13
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
14
name VARCHAR(100) NOT NULL,
15
role VARCHAR(15) NOT NULL,
16
PRIMARY KEY (id)
17
)`;
18
connection.query(query, (error, result) => { // sends queries
19
connection.end(); // closes connection
20
if (error) throw error;
21
console.log(result);
22
});
23
});
Database:

Note:
To create a multi-line string, create a
template literal
usingbackticks
``
.