nadirhussainnn / Utilities

This repository contains small programs , hacks and trciks that are useful for developers
1 stars 0 forks source link

How Connect MySql Database from NodeJS? #8

Open nadirhussainnn opened 3 years ago

nadirhussainnn commented 3 years ago

Steps:

  1. Create Mysql Database in phpmyadmin, Don't forget to start XAMP or MAMP or WAMP server.
  2. Open VS code and execute npm init -y
  3. Create Index.js file, make it main in Package.json
  4. Install nodemon as npm i nodemon
  5. Configure nodemon in Package.json file as

image

  1. Put Following Code in Index.js file
    
    const http=require('http')
    const mysql=require('mysql')    //npm i mysql
    const PORT=5000

const conStr={ host:"localhost", user:"root", password:"", database:"Github_issues_db" } const con=mysql.createConnection(conStr)

const server=http.createServer((req, resp)=>{

con.connect((err)=>{
    if(err)
        return console.error("ERROR OCcured")
    console.log("Connected")
})

})

server.listen(PORT, ()=>{ console.log(SERVER IS LISTENING @ PORT ${PORT}) })


7. Start the Index.js server as `npm start` and visit localhost:5000 in your browser search bar

![image](https://user-images.githubusercontent.com/63782055/126283016-da4ce155-38dc-4b87-a049-cffb8de33ed4.png)