add scan empty check

This commit is contained in:
Jay 2018-04-20 14:34:49 +08:00
parent 04b2cb38b1
commit 4749bdbad3
2 changed files with 13 additions and 13 deletions

View File

@ -10,16 +10,19 @@ import (
) )
// ScanToStruct - scan query rows to struct // ScanToStruct - scan query rows to struct
func ScanToStruct(rows *sql.Rows, ss interface{}) (err error) { func ScanToStruct(rows *sql.Rows, ss interface{}) (ok bool, err error) {
data, err := ResultToMap(rows) data, err := ResultToMap(rows)
if err != nil { if err != nil {
return err return false, err
} }
if len(data) == 0 { if len(data) == 0 {
return nil return false, nil
} }
err = MapToStruct(data[0], ss) err = MapToStruct(data[0], ss)
return nil if err != nil {
return false, err
}
return true, nil
} }
func ScanToStructAll(rows *sql.Rows, ss interface{}) error { func ScanToStructAll(rows *sql.Rows, ss interface{}) error {

15
main.go
View File

@ -17,22 +17,19 @@ type FileT struct {
} }
func main() { func main() {
connStr := "postgres://postgres@localhost:5432/mystorage?sslmode=disable" connStr := "postgres://postgres@localhost:5432/gallery?sslmode=disable"
db, err := sql.Open("postgres", connStr) db, err := sql.Open("postgres", connStr)
handleError(err) handleError(err)
defer db.Close() defer db.Close()
rows, err := db.Query(`select id, name from "storage"."files" where "tmp" = $1 and "trash" = $2 limit 2`, false, false) result, err := db.Query(`insert into "public"."account" ("account", "password", "nick", "email") values ($1, $2, $3, $4) returning *`, "aaaaa", "bbbb", "cccc", "dddd")
handleError(err) handleError(err)
defer rows.Close() defer result.Close()
// mm, err := dbtool.ResultToMap(rows) dd, err := dbtool.ResultToMap(result)
// handleError(err) handleError(err)
var files []FileT fmt.Println(dd)
err = dbtool.ScanToStructAll(rows, &files)
fmt.Println(files)
// var id, name string // var id, name string
// for rows.Next() { // for rows.Next() {