一、问题需求
需要增加一个MySQL Web页面查询的功能,后端为Go开发,前端使用Vue,由于Golang为强类型语言,但数据库查询结果字段并不确定,出现了golang返回结果和数据库实际存储数据存在差异甚至乱码的情况。
二、问题解决
基础环境
- 数据库类型:MySQL
- Go版本:1.13
- Go操作数据库包:Gorm
- 前端使用ui:element ui
后端
cols, err := rows.Columns()
header = cols
for rows.Next() {
columns, err := rows.ColumnTypes()
if err != nil {
return 0, header, nil, err
}
dbtypes := make(map[string]string)
values := make([]interface{}, len(columns))
object := map[string]interface{}{}
for i, column := range columns {
v := reflect.New(column.ScanType()).Interface()
switch v.(type) {
case *[]uint8:
v = new(string)
case *sql.RawBytes:
v = new(*string)
case *mysql.NullTime:
v = new(time.Time)
default:
}
object[column.Name()] = v
values[i] = object[column.Name()]
dbtypes[column.Name()] = column.DatabaseTypeName()
}
err = rows.Scan(values...)
for i,v := range cols {
vs, ok := values[i].(*time.Time)
if !ok {
continue
}
if dbtypes[v] == "DATE" {
object[v] = vs.Format("2006-01-02")
} else {
object[v] = vs.Format("2006-01-02 15:04:05")
}
}
result = append(result, object)
}
后端返回结果示例
"result": [
{
"col": null,
"col100": null,
"col2": null,
"col27": null,
"col3": "",
"col5": null,
"col6": "",
"emp_no": 10101,
"from_date": "1998-10-14",
"iState": "",
"id": 1000,
"salary": 66591,
"to_date": "1999-10-14",
"type": ""
},
{
"col": null,
"col100": null,
"col2": null,
"col27": null,
"col3": "",
"col5": null,
"col6": "",
"emp_no": 10101,
"from_date": "1999-10-14",
"iState": "",
"id": 1001,
"salary": 66715,
"to_date": "2000-09-23",
"type": ""
}
],
"header": [
"emp_no",
"salary",
"from_date",
"to_date",
"id",
"type",
"iState",
"col",
"col2",
"col27",
"col100",
"col3",
"col5",
"col6"
]
前端对应部分
<template>
// 结果展示:header为字段信息,selectResult为查询结果列表
<el-form-item label="查询结果:" prop="sqlSelect" :style=this.sqlSelectResult>
<template>
<el-table :data="selectResult" style="width: 100%" >
<el-table-column v-for="(date, index) in header" :key="index" :label="date" :prop="date" >
<template slot-scope="scope">
{{selectResult[scope.$index][date]}}
</template>
</el-table-column>
</el-table>
</template>
</el-form-item>
</template>
前端显示结果
如果字段名称过长,折行,可以参考http://www.4k8k.xyz/article/guozhangqiang/108094582,根据列名自适应表格宽度,在el-table-column中添加:width="setColumnWidth(date) 即可
|