-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.js
88 lines (80 loc) · 1.97 KB
/
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
const mysql = require('mysql')
const Q = require('q')
var db = mysql.createConnection({
user: 'myuser',
password: 'youxiwang',
database: 'easycar'
})
db.connect(function (error, result) {
if (error) {
return console.log(error)
}
// console.log('connection ok: ' + db.threadId)
})
var insert = function (table, obj) {
if (!table || !obj) {
return false
}
var keys = []
var values = []
for (var key in obj) {
keys.push(key)
// console.log
if (typeof (obj[key]) === 'string') {
obj[key] = "'" + obj[key] + "'"
}
values.push(obj[key])
}
var command = 'INSERT INTO ' + table + '(' + keys.join(',') + ') VALUES(' + values.join(',') + ')'
// console.log(command)
var defered = Q.defer()
db.query(command, defered.makeNodeResolver())
return defered.promise
}
var find = function (table, condition, field) {
if (!field) {
field = '*'
}
if (condition) {
condition = ' WHERE ' + condition
} else {
condition = ''
}
var command = 'SELECT ' + field + ' FROM ' + table + condition
// console.log(command)
var defered = Q.defer()
db.query(command, defered.makeNodeResolver())
return defered.promise
}
var update = function (table, condition, obj) {
if (!condition || !obj) {
return false
}
condition = ' WHERE ' + condition
var strArr = []
for (var key in obj) {
strArr.push(key + '=' + obj[key])
}
var command = 'UPDATE ' + table + ' SET ' + strArr.join(',') + condition
var defered = Q.defer()
db.query(command, defered.makeNodeResolver())
return defered.promise
}
var remove = function (table, condition) {
if (!condition) {
return false
}
condition = ' WHERE ' + condition
var command = 'DELETE FROM ' + table + condition
var defered = Q.defer()
db.query(command, defered.makeNodeResolver())
return defered.promise
}
var close = function () {
db.end()
}
exports.insert = insert
exports.update = update
exports.find = find
exports.remove = remove
exports.close = close