Created
June 21, 2018 12:35
-
-
Save sreepurnajasti/e6555213023771d2ef73673919e7d8d7 to your computer and use it in GitHub Desktop.
Nodejs mysql operations
This file contains 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
var express = require('express'); | |
var app = express(); | |
var bodyParser = require('body-parser'); | |
var mysql = require('mysql'); | |
var con = mysql.createConnection({ | |
host:"localhost", | |
user:"root", | |
passsword:"sree", | |
database:"emp" | |
}); | |
con.connect((err) =>{ | |
if(err) throw err; | |
console.log('connected'); | |
}) | |
app.use( bodyParser.json() ); // to support JSON-encoded bodies | |
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies | |
extended: true | |
})); | |
app.use(express.static('public')); | |
app.get('/', function (req, res) { | |
res.sendFile( __dirname + "/" + "main.html" ); | |
}); | |
app.get('/display',function(req, res){ | |
let sql = `SELECT * FROM details ORDER By id`; | |
operations(sql, res); | |
}) | |
app.post('/edit', (req, res) => { | |
console.log(req.body); | |
let sql = `UPDATE details SET name='${req.body.emName}', designation='${req.body.emDes}', company='${req.body.emCom}', email='${req.body.emEmail}' WHERE id=${req.body.emId}`; | |
operations(sql, res); | |
}) | |
function operations(sql, res){ | |
let response = {}; | |
con.query(sql, function(err, result, fields) { | |
if(err){ | |
response.successful = false; | |
console.error(err); | |
console.log(JSON.stringify(result)); | |
res.send(JSON.stringify(response)); | |
return response; | |
}else{ | |
if(Array.isArray(result)){ | |
if(result.length>0){ | |
response.data = result; | |
response.successful = true; | |
res.send(JSON.stringify(response)); | |
return response; | |
}else{ | |
response.successful = false; | |
res.send(JSON.stringify(response)); | |
return response; | |
} | |
}else{ | |
if(result.affectedRows>0){ | |
response.successful = true; | |
res.send(JSON.stringify(response)); | |
return response; | |
}else{ | |
response.successful = false; | |
res.send(JSON.stringify(response)); | |
return response; | |
} | |
} | |
} | |
}) | |
} | |
var server = app.listen(8081); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment