popoola Temitope
Posted on August 9, 2021
Connecting node.js project with MySQL database is easy, follow the following steps to connect to the the database
By reading this article I believe you have installed nodee Js on your system and familiar with it.
Step1
Open your code editor.
Step2
Create a new project
Open your command prompt or terminal and enter
mkdir project_name
cd project_name
Step3
Create project file.
enter
npm init -y
into the command prompt or terminal.
Step4
To be able to connect to mysql database you need to install MySQL module into your project.
To do this is very simple, open your CMD or terminal and enter
npm install mysql
this command will install the module into your project.
Step5
Now we can open connection From our project code to mysql database
add the code below to your app.js code to open a connection.
const mysql = require('mysql');
// Creating a mysql connection
const conn = mysql.createConnection({
host: "localhost",
user: "db_username",
password: "db_password",
database: "db_name"
});
Step6
Let create a simple database and table
conn.connect((err)=>{
if (err) throw err;
console.log("Database connected successful");
var sql = "CREATE TABLE books (book_name VARCHAR(255), book_description VARCHAR(255))";
con.query(sql,(err, result)=> {
if (err) throw err;
console.log("Table created");
});
});
You can leave a comment...
Thanks❤️
Posted on August 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024