-
Notifications
You must be signed in to change notification settings - Fork 0
/
gosqltool.go
99 lines (81 loc) · 1.97 KB
/
gosqltool.go
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
package gosqltool
import (
"database/sql"
"fmt"
"github.com/beevik/etree"
)
// XML default table name and row name
var (
TableName = "RowData"
RowName = "Row_"
)
// RowsToMap transfer sql res to map
// dataMap[rowCnt]map[colName]value
func RowsToMap(rows *sql.Rows) (dataRes map[int]map[string]string, err error) {
dataMap := make(map[int]map[string]string)
cols, err := rows.Columns()
if err != nil {
return
}
rawResult := make([][]byte, len(cols))
dest := make([]interface{}, len(cols)) // A temporary interface{} slice
for i := range rawResult {
dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
}
rowCnt := 0
for rows.Next() {
rowMap := make(map[string]string)
err = rows.Scan(dest...)
if err != nil {
return
}
for i, raw := range rawResult {
rowMap[cols[i]] = string(raw)
}
dataMap[rowCnt] = rowMap
rowCnt = rowCnt + 1
}
if dataMap != nil {
dataRes = dataMap
}
return
}
// RowsToXML transfer sql res to xml
// <?xml version="1.0" encoding="UTF-8"?>
// <[tableName]> (default "RowDAta")
// <[rowName]0> (default "Row_0")
// <[KEY1]>[VALUE1]</[KEY1]>
// <[KEY2]>[VALUE2]</[KEY2]>
// </[rowName]0>
// </[tableName]>
func RowsToXML(rows *sql.Rows) (xmlString string, err error) {
cols, err := rows.Columns()
if err != nil {
return
}
xmlString = cols[0]
rawResult := make([][]byte, len(cols))
dest := make([]interface{}, len(cols))
for i := range rawResult {
dest[i] = &rawResult[i]
}
xml := etree.NewDocument()
xml.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
rowData := xml.CreateElement(TableName)
rowCnt := 0
for rows.Next() {
err = rows.Scan(dest...)
if err != nil {
return
}
rowElement := rowData.CreateElement(fmt.Sprintf("%s%d", RowName, rowCnt))
for i, raw := range rawResult {
colName := rowElement.CreateElement(cols[i])
colName.CreateText(string(raw))
}
rowCnt = rowCnt + 1
}
xml.Indent(2)
xmlString, err = xml.WriteToString()
return
}