-
Notifications
You must be signed in to change notification settings - Fork 3
/
dbmysql.js
executable file
·69 lines (58 loc) · 1.65 KB
/
dbmysql.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* jshint node: true */
'use strict';
var mysql = require('mysql');
var db = {
getConnection: function(conf){
//try making a connection to mysql
//
var conn = mysql.createConnection(conf);
conn.on('error', function(err){
console.log('dberror: '+err);
});
return conn;
},
insert: function(conf, sql, params, callback){
var conn = db.getConnection(conf);
conn.connect(function(err){
/* istanbul ignore if */
if( err )
return callback(true, 'insert: db connection failed '+err.message);
conn.query(sql, params, function(err, res){
conn.end();
if( err )
return callback(err, err.message);
return callback(err, res.insertId);
});
});
},
query: function(conf, sql, params, callback){
var conn = db.getConnection(conf);
conn.connect(function(err){
/* istanbul ignore if */
if( err )
return callback(true, 'query: db connection failed '+err.message);
conn.query(sql, params, function(err, rows, fields){
conn.end();
return callback(err, rows, fields);
});
});
},
queryArray: function(conf, sql, params, callback){
db.query(conf, sql, params, function(err, rows, fields){
var arr = [];
if( !err )
for( var i in rows )arr.push(rows[i][fields[0].name]);
return callback(err, arr);
});
},
getColumnNames: function(conf, tableName, callback){
var sql = "show columns from "+tableName;
db.query(conf, sql, [], function(err, rows, fields){
if( err )return callback(err, rows);
var arr = [];
for( var i in rows )arr.push(rows[i].Field);
return callback(err, arr);
});
},
};
module.exports = db;