-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_mysql.js
122 lines (104 loc) · 2.41 KB
/
db_mysql.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
var mysql = require('mysql');
var config=require('../config');
var DB={};
/*
* @param table 表名 String
* @param fileds 字段 Array
* @param where 条件 Object
*/
DB.getOne = function (table,fileds,wheres,callback) {
var filed = '' ,where = '';
if (fileds && fileds.length > 0 ){
for (var i = 0 ; i< fileds.length ; i++){
filed += fileds[i] + ',';
}
filed = filed.substring(0,filed.length-1);
}else{
filed += "*";
};
if (wheres){
where += ' where '
for(var i in wheres){
where += ' ' + i + ' = "' + wheres[i] +'" '
}
}else {
where += " where 1";
};
var sql = 'select '+ filed +' from ' + table + where +' limit 1' ;
DB.execs(sql,function (err,rows) {
callback(rows[0])
})
};
DB.getAll = function (table,fileds,wheres,callback) {
var filed = '' ,where = '';
if (fileds && fileds.length > 0 ){
for (var i = 0 ; i< fileds.length ; i++){
filed += fileds[i]+ ',';
}
filed = filed.substring(0,filed.length-1);
}else{
filed += "*";
};
if (wheres && (typeof(wheres) == "undefined")){
where += ' where '
for(var i in wheres){
where += ' ' + i + wheres[i] +' '
}
}else {
where += " where 1";
};
var sql = 'select '+ filed +' from ' + table + where ;
DB.execs(sql,function (err,rows) {
callback(rows)
})
};
DB.delete = function (table,where,callback) {
var db = table;
if (typeof where === 'object'){
DB.fetch(where,function (fwhere) {
var sql = 'delete from ' + table + fwhere;
DB.execs(sql,function (err,rows) {
callback(rows)
})
})
}
};
DB.update = function () {
var sql = '';
DB.execs(sql,function (err,rows) {
callback(rows)
});
};
DB.insert = function () {
var sql = '';
DB.execs(sql,function (err,rows) {
callback(rows)
});
};
DB.execs = function (sql,callback) {
DB.connects().query(sql,function (err, rows, fields) {
callback(err,rows);
});
};
DB.fetch = function (where,callback) {
var swhere = ' where ';
for(var i in where){
swhere += i + ' = "' + where[i] + '" AND ';
}
swhere += ' 1 ';
callback(swhere);
}
//连接数据库
DB.connects = function () {
var option = {
host: config.mysql.db_host,
port: config.mysql.db_port,
user: config.mysql.username,
password: config.mysql.password,
database: config.mysql.db_name
};
var instance = mysql.createConnection(option);
instance.connect();
return instance;
};
module.exports = DB;