
Mysql Create Table in NodeJs
Creating a MySQL table in Node.js is a common next step after creating a database. You can do it using either the mysql
or mysql2
package.
Hereβs how you do it π
β Step 1: Install MySQL Package
npm install mysql
Or if you prefer async/await:
npm install mysql2
π οΈ Step 2: Connect to the Database and Create a Table
Using mysql
(Callback style):
const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' // π Replace with your actual DB name});connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL!'); const sql = ` CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), age INT ) `; connection.query(sql, (err, result) => { if (err) throw err; console.log('Table created!'); connection.end(); });});
Using mysql2
(Async/Await):
const mysql = require('mysql2/promise');async function createTable() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase' }); const sql = ` CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), age INT ) `; await connection.query(sql); console.log('Table created!'); await connection.end();}createTable();
π§ Customize Your Table
You can add other column types:
TEXT
for large stringsBOOLEAN
for true/falseTIMESTAMP
for created/updated times
Example:
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
Need help with:
Inserting data into the table?
Querying or updating it?
Creating foreign keys or constraints?