在Golang的GORM中,”Select all”不起作用。

huangapple go评论90阅读模式
英文:

Select all is not working in golaong gorm

问题

我正在使用gin框架,并尝试使用grom进行CRUD操作。我正在尝试从MYSQL数据库中获取数据。我有一个db.go文件来获取数据库实例,一些控制器用于每个表和模型。

我有一个如下所示的模型:

type Campaigns struct {
    ID                     int       `json:"id" form:"id" gorm:"column:CampaignID"`
    UserID                 int       `json:"userId" form:"userId" gorm:"column:UserID"`
    Name                   string    `json:"name" form:"name" gorm:"column:Name"`
    StartDate              time.Time `json:"start" form:"start" gorm:"column:StartDate"`
    EndDate                time.Time `json:"end" form:"end" gorm:"column:EndDate"`
    Customer               string    `json:"customer" form:"customer" gorm:"column:Customer"`
    CustomerID             int       `json:"customerId" form:"customerId" gorm:"column:CustomerID"`
    ImpressionsCounter     int       `json:"ImpressionsCounter" form:"ImpressionsCounter" gorm:"column:ImpressionsCounter"`
    MaxImpressions         int       `json:"maxImpressions" form:"maxImpressions" gorm:"column:MaxImpressions"`
    CurrentSpend           float64   `json:"currentSpend" gorm:"column:CurrentSpend"`
    MaxSpend               float64   `json:"maxSpend" form:"maxSpend" gorm:"column:MaxSpend"`
    Active                 bool      `json:"active" form:"active" gorm:"column:Active"`
    Created                time.Time `json:"created" gorm:"column:DateCreated"`
    Updated                time.Time `json:"updated" gorm:"column:DateCreated"`
}

这是一个我正在使用的控制器:

package controllers

import (
    "time"

    "github.com/op/go-logging"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/go-sql-driver/mysql"

    "../models"
)

var log = logging.MustGetLogger("AsAPI")

type AsController struct {
    DB gorm.DB
}

func (ac *AsController) SetDB(d gorm.DB) {
    ac.DB = d
    ac.DB.LogMode(true)
}

// 获取所有表
func (ac *AsController) ListTable(c *gin.Context) {

    var results []models.Campaigns
    err := ac.DB.Find(&results)

    if err != nil {
        log.Debugf("Error when looking up Table, the error is '%v'", err)
        res := gin.H{
            "status": "404",
            "error":  "No Table found",
        }
        c.JSON(404, res)
        return
    }
    content := gin.H{
        "status": "200",
        "result": "Success",
        "Table":  results,
    }

    c.Writer.Header().Set("Content-Type", "application/json")
    c.JSON(200, content)
}

要获取数据库连接,我正在使用以下代码:

package controllers

import (
    "time"

    "github.com/op/go-logging"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/go-sql-driver/mysql"

    "../models"
)

var log = logging.MustGetLogger("AdsAPI")

type AsController struct {
    DB gorm.DB
}

func (ac *AsController) SetDB(d gorm.DB) {
    ac.DB = d
    ac.DB.LogMode(true)
}

我正在使用以下路由:

ac := controllers.AdsController{}
ac.SetDB(dc.GetDB())

// 获取Ads资源
router := gin.Default()

router.GET("/table", ac.ListTables)

当我运行这段代码时,我得到以下错误:

(/api/controllers/table.go:30)
[2016-03-23 09:56:39] [0.99ms] SELECT * FROM `tables`
2016/03/23 09:56:39 Error when looking up tables, the error is '&{0xc8202140e0 sql: Scan error on column index 3: unsupported driver -> Scan pair: []uint8 -> *time.Time 1 <nil> 0xc82022f860 0xc82022f7c0 0xc82021e140 2 {0xc8201fb4a0} <nil> false map[] map[]}'
[GIN] 2016/03/23 - 09:56:39 | 404 | 1.153811ms | 127.0.0.1 | GET /table

这个错误的原因是什么?帮我修复这个错误。

英文:

I'm using gin framework and trying do crud operation using grom.I'm trying to get data from MYSQL database. i have db.go to get database instances, some controllers to each table and models
i have a model like this

    type Campaigns struct {

		ID                     int       `json:&quot;id&quot; form:&quot;id&quot; gorm:&quot;column:CampaignID&quot;`
		UserID                 int       `json:&quot;userId&quot; form:&quot;userId&quot; gorm:&quot;column:UserID&quot;`
		Name                   string    `json:&quot;name&quot; form:&quot;name&quot; gorm:&quot;column:Name&quot;`
		StartDate              time.Time `json:&quot;start&quot; form:&quot;start&quot; gorm:&quot;column:StartDate&quot;`
		EndDate                time.Time `json:&quot;end&quot; form:&quot;end&quot; gorm:&quot;column:EndDate&quot;`
		Customer               string    `json:&quot;customer&quot; form:&quot;customer&quot; gorm:&quot;column:Customer&quot;`
		CustomerID             int       `json:&quot;customerId&quot; form:&quot;customerId&quot; gorm:&quot;column:CustomerID&quot;`
		ImpressionsCounter     int       `json:&quot;ImpressionsCounter&quot; form:&quot;ImpressionsCounter&quot; gorm:&quot;column:ImpressionsCounter&quot;`
		MaxImpressions         int       `json:&quot;maxImpressions&quot; form:&quot;maxImpressions&quot; gorm:&quot;column:MaxImpressions&quot;`
		CurrentSpend           float64   `json:&quot;currentSpend&quot; gorm:&quot;column:CurrentSpend&quot;`
		MaxSpend               float64   `json:&quot;maxSpend&quot; form:&quot;maxSpend&quot; gorm:&quot;column:MaxSpend&quot;`
		Active                 bool      `json:&quot;active&quot; form:&quot;active&quot; gorm:&quot;column:Active&quot;`
		Created                time.Time `json:&quot;created&quot; gorm:&quot;column:DateCreated&quot;`
		Updated                time.Time `json:&quot;updated&quot; gorm:&quot;column:DateCreated&quot;`
}

this is a one controller I'm using

    package controllers
import (
	&quot;time&quot;

  &quot;github.com/op/go-logging&quot;
	&quot;github.com/gin-gonic/gin&quot;
	&quot;github.com/jinzhu/gorm&quot;
  _ &quot;github.com/go-sql-driver/mysql&quot;

	&quot;../models&quot;
)

var log = logging.MustGetLogger(&quot;AsAPI&quot;)

type AsController struct {
	DB gorm.DB
}

func (ac *AsController) SetDB(d gorm.DB) {
	ac.DB = d
	ac.DB.LogMode(true)
}


// Get all table
func (ac *AsController) ListTable(c *gin.Context) {

	var results []models.Campaigns
  err := ac.DB.Find(&amp;results)

	if err != nil {
		log.Debugf(&quot;Error when looking up Table, the error is &#39;%v&#39;&quot;, err)
		res := gin.H{
				&quot;status&quot;: &quot;404&quot;,
				&quot;error&quot;: &quot;No Table found&quot;,
		}
		c.JSON(404, res)
		return
	}
	content := gin.H{
						&quot;status&quot;: &quot;200&quot;,
            &quot;result&quot;: &quot;Success&quot;,
            &quot;Table&quot;: results,
        }

  c.Writer.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
  c.JSON(200, content)
}

To get database connection I'm using

package controllers
import (
	&quot;time&quot;

  &quot;github.com/op/go-logging&quot;
	&quot;github.com/gin-gonic/gin&quot;
	&quot;github.com/jinzhu/gorm&quot;
  _ &quot;github.com/go-sql-driver/mysql&quot;

	&quot;../models&quot;
)

var log = logging.MustGetLogger(&quot;AdsAPI&quot;)

type AsController struct {
	DB gorm.DB
}

func (ac *AsController) SetDB(d gorm.DB) {
	ac.DB = d
	ac.DB.LogMode(true)
} 

and I'm using following routs

ac := controllers.AdsController{}
ac.SetDB(dc.GetDB())


// Get a Ads resource
router := gin.Default()

router.GET(&quot;/table&quot;, ac.ListTables)

when i run this I'm getting following error

(/api/controllers/table.go:30) 
[2016-03-23 09:56:39]  [0.99ms]  SELECT  * FROM `tables`  
2016/03/23 09:56:39 Error when looking up tables, the error is &#39;&amp;{0xc8202140e0 sql: Scan error on column index 3: unsupported driver -&gt; Scan pair: []uint8 -&gt; *time.Time 1 &lt;nil&gt; 0xc82022f860 0xc82022f7c0 0xc82021e140 2 {0xc8201fb4a0} &lt;nil&gt; false  map[] map[]}&#39;
[GIN] 2016/03/23 - 09:56:39 | 404 |    1.153811ms | 127.0.0.1 |   GET     /table

what is the reason for this error ? help me to fix this error ?

答案1

得分: 1

你可以在驱动程序文档中找到答案,链接如下:
https://github.com/go-sql-driver/mysql#timetime-support

MySQL DATE 和 DATETIME 值的默认内部输出类型是 []byte,这允许你将该值扫描到 []byte、string 或 sql.RawBytes 变量中。

然而,许多人希望将 MySQL DATE 和 DATETIME 值扫描到 time.Time 变量中,这在 Go 中与 MySQL 的 DATE 和 DATETIME 是逻辑上的相反。你可以通过将内部输出类型从 []byte 更改为 time.Time,并使用 DSN 参数 parseTime=true 来实现。你可以使用 loc DSN 参数设置默认的 time.Time 位置。

或者,你可以使用 NullTime 类型作为扫描目标,它可以同时与 time.Time 和 string / []byte 一起使用。

英文:

You can find the answer in the driver documentation
https://github.com/go-sql-driver/mysql#timetime-support:

> The default internal output type of MySQL DATE and DATETIME values is []byte which allows you to scan the value into a []byte, string or sql.RawBytes variable in your programm.
>
> However, many want to scan MySQL DATE and DATETIME values into time.Time variables, which is the logical opposite in Go to DATE and DATETIME in MySQL. You can do that by changing the internal output type from []byte to time.Time with the DSN parameter parseTime=true. You can set the default time.Time location with the loc DSN parameter.
>
> Alternatively you can use the NullTime type as the scan destination, which works with both time.Time and string / []byte.

答案2

得分: -3

你在这里是否真的打开了数据库?我根本没有看到任何实际的Open()调用...

英文:

Are you ever actually opening the database here? I don't see an actual Open() call in there at all...

huangapple
  • 本文由 发表于 2016年3月23日 13:14:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/36170330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定