forked from ewintec/nodejs-rinho-udp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
47 lines (44 loc) · 1.23 KB
/
db.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Requires
var util = require("./util.js");
// DB Connection
exports.connection = null;
// Init DB
exports.init = function() {
var callback = this;
function kickWatchDog() {
try { this.connection.end(); } catch(e) {}
setTimeout(function () { require('./db.js').init(); }, 5000);
}
util.log("DB INIT, Starting DB");
var mysql = require('mysql');
this.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'rinhonode'
});
this.connection.on('error', function(err) {
util.log("DB ERROR, Disconected DB!");
util.log("DB ERROR, " + err);
kickWatchDog();
});
this.connection.connect(function(err) {
if (err) {
util.log("DB ERROR, Disconected DB!");
util.log("DB ERROR, " + err);
kickWatchDog();
}
});
}
// Prepares a SQL Insert from an associative array
exports.prepareInsert = function(data, table) {
var values = [], keys = [];
for (var key in data) {
if (data[key] == null) values.push("NULL");
else if (key == "createdAt" || key == "modifiedAt") values.push(data[key]);
else values.push("'"+data[key]+"'");
keys.push(key);
}
var sqlString = "INSERT INTO "+ table +" (" + keys.join(',') + ") VALUES(" + values.join(',') + ")";
return sqlString;
}