1.2 SQL操作

1.2.1【必须】SQL语句默认使用预编译并绑定变量

  • 使用database/sql的prepare、Query或使用GORM等ORM执行SQL操作
  1. import (
  2. "github.com/jinzhu/gorm"
  3. _ "github.com/jinzhu/gorm/dialects/sqlite"
  4. )
  5. type Product struct {
  6. gorm.Model
  7. Code string
  8. Price uint
  9. }
  10. ...
  11. var product Product
  12. db.First(&product, 1)
  • 使用参数化查询,禁止拼接SQL语句,另外对于传入参数用于order by或表名的需要通过校验
  1. // bad
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "net/http"
  6. )
  7. func handler(db *sql.DB, req *http.Request) {
  8. q := fmt.Sprintf("SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='%s' ORDER BY PRICE",
  9. req.URL.Query()["category"])
  10. db.Query(q)
  11. }
  12. // good
  13. func handlerGood(db *sql.DB, req *http.Request) {
  14. //使用?占位符
  15. q := "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='?' ORDER BY PRICE"
  16. db.Query(q, req.URL.Query()["category"])
  17. }