Last active
July 26, 2017 19:24
-
-
Save Antoinebr/c1178a97a8436325af899893c4ada538 to your computer and use it in GitHub Desktop.
node mysql db connect and record
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 dataBase = require('./db.js'); | |
/* | |
* Instatiations | |
*/ | |
var db = new dataBase(); | |
try { | |
db.isNewUrl(data.final_urls, function (res) { | |
try { | |
db.recordRedirection({ cid: data.final_url_cid, date: data.date, url_origine: origine, url_destination: res }); | |
} catch (e) { console.log(e) } | |
}); | |
}catch(e) { | |
console.log(e) | |
} | |
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 db = function () { | |
this.mysql = require("mysql"); | |
var jsesc = require('jsesc'); | |
this.con = null; | |
this.connectToDb = function(){ | |
this.con = this.mysql.createConnection({ | |
host: "localhost", | |
user: "root", | |
password: "root", | |
database: "redirections", | |
port: 8889 | |
}); | |
this.con.connect(function(err){ | |
if(err) throw err; | |
console.log('Connection established'); | |
}); | |
}; | |
this.isNewUrl = function(url,callback){ | |
// sanitize | |
var url = jsesc(url); | |
this.con.query("SELECT COUNT('url_origine') AS urlCount FROM list WHERE url_origine = '"+url+"' ",function(err,res){ | |
if(err) throw err; | |
var isNew = (res[0].urlCount > 0) ? false : true; | |
callback(isNew); | |
}); | |
} | |
this.recordRedirection = function(dataToInsert){ | |
var that = this; | |
// sanitize | |
dataToInsert.url_destination = jsesc(dataToInsert.url_destination); | |
that.con.query('INSERT INTO list SET ?', dataToInsert, function(err,res){ | |
if(err) throw err; | |
console.log('Last insert ID:', res.insertId); | |
}); | |
}; | |
}; | |
module.exports = db; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment