无法使用*db.rows()获取所有行

6ie5vjzr  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(420)

我是刚来戈姆的,所以如果我误解了什么,请指出。
我正在使用mysql编写小型应用程序,我决定使用gorm作为orm。源代码和输出如下。

package main

import (
    "fmt"
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Group struct {
    gorm.Model
    Name string `gorm:"not null;unique"`
}

func openDB() *gorm.DB {
    user := "ipmonitor"
    password := "testpassword"
    database := "ipmonitor"

    mysqlURL := "%s:%s@/%s?charset=utf8mb4&parseTime=True&loc=Local"

    db, err := gorm.Open("mysql", fmt.Sprintf(mysqlURL, user, password, database))
    if err != nil {
        log.Fatalln(err)
    }

    return db
}

func initDB(db *gorm.DB) {
    db = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
    db.AutoMigrate(&Group{})

    result := db.Create(&Group{Name: "foo"})
    if result.Error != nil {
        log.Fatalln(result.Error)
    }
    result = db.Create(&Group{Name: "bar"})
    if result.Error != nil {
        log.Fatalln(result.Error)
    }
    result = db.Create(&Group{Name: "baz"})
    if result.Error != nil {
        log.Fatalln(result.Error)
    }
}

func main() {
    db := openDB()
    db.LogMode(true)
    initDB(db)

    records := db.Find(&Group{})
    if records.Error != nil {
        log.Fatalln(records.Error)
    }

    log.Printf("%d rows found.", records.RowsAffected)
    rows, err := records.Rows()
    if err != nil {
        log.Fatalln(err)
    }
    defer rows.Close()

    for rows.Next() {
        var group Group
        err := db.ScanRows(rows, &group)
        if err != nil {
            log.Fatalln(err)
        }

        log.Printf("%+v\n", group)
    }
    if rows.Err() != nil {
        log.Fatalln(rows.Err())
    }
}

输出

(dbtest.go:33)
[2018-07-30 18:12:33]  [9.96ms]  CREATE TABLE `groups` (`id` int unsigned AUTO_INCREMENT,`created_at` timestamp NULL,`updated_at` timestamp NULL,`deleted_at` timestamp NULL,`name` varchar(255) NOT NULL UNIQUE , PRIMARY KEY (`id`)) ENGINE=InnoDB CHARSET=utf8mb4
[0 rows affected or returned ]

(dbtest.go:33)
[2018-07-30 18:12:33]  [6.95ms]  CREATE INDEX idx_groups_deleted_at ON `groups`(deleted_at)
[0 rows affected or returned ]

(dbtest.go:35)
[2018-07-30 18:12:33]  [0.89ms]  INSERT INTO `groups` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES ('2018-07-30 18:12:33','2018-07-30 18:12:33',NULL,'foo')
[1 rows affected or returned ]

(dbtest.go:39)
[2018-07-30 18:12:33]  [0.99ms]  INSERT INTO `groups` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES ('2018-07-30 18:12:33','2018-07-30 18:12:33',NULL,'bar')
[1 rows affected or returned ]

(dbtest.go:43)
[2018-07-30 18:12:33]  [0.88ms]  INSERT INTO `groups` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES ('2018-07-30 18:12:33','2018-07-30 18:12:33',NULL,'baz')
[1 rows affected or returned ]

(dbtest.go:54)
[2018-07-30 18:12:33]  [0.63ms]  SELECT * FROM `groups`  WHERE `groups`.`deleted_at` IS NULL
[3 rows affected or returned ]
2018/07/30 18:12:33 3 rows found.

(dbtest.go:60)
[2018-07-30 18:12:33]  [0.77ms]  SELECT * FROM `groups`  WHERE `groups`.`deleted_at` IS NULL AND `groups`.`id` = '3'
[0 rows affected or returned ]
2018/07/30 18:12:33 {Model:{ID:3 CreatedAt:2018-07-30 18:12:34 +0900 JST UpdatedAt:2018-07-30 18:12:34 +0900 JST DeletedAt:<nil>} Name:baz}

mysql数据库

mysql> select * from groups;
+----+---------------------+---------------------+------------+------+
| id | created_at          | updated_at          | deleted_at | name |
+----+---------------------+---------------------+------------+------+
|  1 | 2018-07-30 18:12:34 | 2018-07-30 18:12:34 | NULL       | foo  |
|  2 | 2018-07-30 18:12:34 | 2018-07-30 18:12:34 | NULL       | bar  |
|  3 | 2018-07-30 18:12:34 | 2018-07-30 18:12:34 | NULL       | baz  |
+----+---------------------+---------------------+------------+------+
3 rows in set (0.00 sec)

我希望如此 *DB.Find().Rows() 方法返回多行,但似乎只返回最后一行。
根据gorm调试输出,似乎在执行select语句时添加了未指定的条件。
在谷歌搜索之后,我找不出问题的原因。为什么我的代码不起作用?
谢谢。

von4xj4u

von4xj4u1#

您可以尝试这种替代方法:

var records []Group
db.Find(&records)

所有数据都将以数组的形式提供 records .
如果需要处理错误:

if err := db.Find(&records).Error; err != nil {
  log.Fatalln(err)
}
log.Printf("%d rows found.", len(records))

相关问题