Created
May 10, 2018 04:20
-
-
Save byJeevan/431bb1c5075bc14ab7f73fe115e9ecca to your computer and use it in GitHub Desktop.
Connecting NodeJS with MySQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Sample code to connect MySQL DB in NodeJS | |
* Table name: user | |
* Test Result : Pass | |
* Pre-requesties : NodeJS installed with Express, MySql dependencies. | |
*/ | |
var express = require("express") | |
var mysql = require('mysql') | |
var app = express() | |
app.listen(3306) | |
app.get("/user", (req, res) => { | |
var connection = mysql.createConnection({ | |
host : 'localhost', | |
user : 'root', | |
password : '', | |
database : 'mydb' | |
}); | |
connection.connect(function(err){ | |
if(!err) { | |
console.log("Database is connected ... \n\n"); | |
} else { | |
console.log("Error connecting database ... \n\n"); | |
} | |
}); | |
connection.query("select * from user", (err, rows, fields) => { | |
console.log("Users loaded") | |
res.json(rows) | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment