2016-03-23 2 views
0

Я использую gin framework и пытаюсь выполнить crud-операцию с помощью grom.I'm пытается получить данные из базы данных MYSQL. я db.go получить экземпляры базы данных, некоторые контроллеры для каждой таблицы и модели у меня есть модель, как этотВыделить все не работает в golaong gorm

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) 
} 


// Get all table 
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()) 


// Get a Ads resource 
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 

, что является причиной этой ошибки? Помогите мне исправить эту ошибку?

ответ

1

Вы можете найти ответ в документации драйвера https://github.com/go-sql-driver/mysql#timetime-support:

Тип внутреннего вывода по умолчанию DATE и DATETIME значений MySQL является [] байт, который позволяет сканировать значение в [] байт, string или sql.RawBytes в вашей программе.

Однако многие хотят сканировать значения DATE и DATETIME MySQL во времени. Временные переменные, которые являются логическими противоположными в Go to DATE и DATETIME в MySQL. Вы можете это сделать, изменив тип внутреннего вывода с [] байт на время. Время с параметром DSN parseTime = true. Вы можете установить время по умолчанию time.Time с параметром loc DSN.

В качестве альтернативы вы можете использовать тип NullTime в качестве места назначения сканирования, который работает как с часами time.Time, так и с строкой/[].

+0

ok Я попробовал другое приложение, которое не имеет значений DATETIME, но имеет только int и строку. У меня такая же ошибка. –

+0

это проект, который я использовал для тестирования https://bitbucket.org/nuwan600/golang/src –

+0

ребята, любое другое предложение, если у вас есть, пожалуйста, дайте мне знать ... –

-1

Вы когда-нибудь открывали базу данных здесь? Я вообще не вижу фактического вызова Open() ...