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❤️
Top comments (7)
Great intro! The same tutorial will work for MariaDB, as the protocols are compatible.
Furthermore, one can use
npm install mariadb
to get the MariaDB connector which is a little bit faster instead.You're the best one
Merci
je vous admire tous pour le bonheur que vous orchestrez dans la Dev community
Soyez bénis
Awesome...
mysql2
is with better performance: github.com/sidorares/node-mysql2/b...Thanks for this post
I think, using sequelize to work for MySQL will be more helpful.
sequelize.org/