改进代码if startT == "" || endT == "" { sqlstr = "" } else { var buf bytes.Buffer fmt.Fprintf(&buf, "AND created_at BETWEEN %s AND %s", startT, endT) sqlstr = buf.String() } res := common.DB.Raw("SELECT * FROM(SELECT id,created_at,type,source,explanation,label,location,facility_id,pm_id FROM flaws WHERE facility_id = ? "+sqlstr, "UNION SELECT id,created_at,type,source,explanation,label,location,facility_id,pm_id FROM issues WHERE facility_id = ? "+sqlstr, "UNION SELECT id,created_at,type,source,explanation,label,location,facility_id,pm_id FROM records WHERE facility_id = ? "+sqlstr, "UNION SELECT id,created_at,type,source,explanation,label,location,facility_id,pm_id FROM qualities WHERE facility_id = ? "+sqlstr, "UNION SELECT id,created_at,type,source,explanation,label,location,facility_id,pm_id FROM inspections WHERE facility_id = ?)"+sqlstr, "AS combined_tables LIMIT ? OFFSET ?", code, code, code, code, code, pageSize, offset).Find(&req)
时间: 2024-02-09 21:12:18 浏览: 179
中国移动一级BOSS接口规范-农信通业务单行本154.docx
这段代码已经比较简洁和清晰,但还可以做一些改进。下面是一些可能的改进方向:
1. 使用预处理语句避免 SQL 注入漏洞。在 Go 语言中,可以使用 database/sql 包中的 Prepare 和 Exec 函数来执行预处理语句,这样可以避免 SQL 注入漏洞。
2. 使用常量或变量来存储查询语句的模板,避免在代码中硬编码 SQL 查询语句。这样可以提高代码的可读性和可维护性。
3. 将查询语句和查询参数分开处理,避免将查询参数直接拼接到查询语句中,提高代码的可读性和可维护性。
4. 对于大型的 SQL 查询语句,可以使用多行字符串来存储查询语句,提高代码的可读性。例如:
```
sql := `SELECT *
FROM table1
JOIN table2 ON table2.id = table1.table2_id
WHERE table1.id = ?`
```
5. 使用结构体来存储查询参数,提高代码的可读性和可维护性。例如:
```
type QueryParams struct {
Code string
StartT string
EndT string
PageSize int
Offset int
}
func GetQueryResults(params QueryParams) ([]Record, error) {
// ...
}
```
阅读全文