【问题标题】:Golang API - MySQL connects but queries emptyGolang API - MySQL 连接但查询为空
【发布时间】:2017-02-16 00:08:15
【问题描述】:

让我先说我是 Golang 的新手,并且正在使用 Golang 重构现有的基于 Python 的 API,因此数据库和底层架构已经存在并填充了数据。

我有一个使用 Gin 和 Gorm 的非常基本的 API 设置。在 GET API 调用期间,它能够连接到 MySQL 5.7 后端,但我的任何查询都不会返回任何内容。我已经尝试了各种具有已知序列号的查询,这些查询在数据库中并且在我在此应用程序之外查询时返回。

ma​​in.go

package main

import (
    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
    "time"
    "log"
    "fmt"
)

var db *gorm.DB

func InitDB() *gorm.DB{
    var err error
    db, err := gorm.Open("mysql", "api:MyPassword@tcp(10.37.1.1:3306)/opt_db1")
    db.SingularTable(true)

    err = db.DB().Ping()

    if err != nil {
        log.Panic(err)
        fmt.Print(err.Error())
    } else {
        fmt.Printf("Successfully connected to MySQL")
    }

    return db
}

type TestResult struct {
    ID                    int  `db:"id" json:"id"`
    DateAdded             time.Time `db:"date_added" json:"date_added"`
    Serial                string  `db:"serial" json:"serial"`
    SequenceId            int `db:"sequence_id" json:"sequence_id"`
    LastCompletedStage    int `db:"last_completed_stage" json:"last_completed_stage"`
    LastCompletedSequence int `db:"last_completed_sequence" json:"last_completed_sequence"`
    Workorder             string  `db:"workorder" json:"workorder"`
    Product               string `db:"product" json:"product"`
    IsComplete            string `db:"is_complete" json:"is_complete"`
    IsScrapped            string `db:"is_scrapped" json:"is_scrapped"`
    ValueStream           string `db:"value_stream" json:"value_stream"`
    PromiseDate           string `db:"promise_date" json:"promise_date"`
    FailLock              int `db:"fail_lock" json:"fail_lock"`
    SequenceRev           int `db:"sequence_rev" json:"sequence_rev"`
    DateUpdated           time.Time `db:"date_updated" json:"date_updated"`
    Date                  time.Time `db:"date" json:"date"`
    Time                  time.Time `db:"time" json:"time"`
    Ptyp2                 string `db:"ptyp2" json:"ptyp2"`
    WoQty                 int `db:"wo_qty" json:"wo_qty"`
    IsActive              int `db:"is_active" json:"is_active"`
    IsTimeLock            int `db:"is_time_lock" json:"is_time_lock"`
    TimeLockTimestamp     time.Time `db:"time_lock_timestamp" json:"time_lock_timestamp"`
    ScrapReason           string `db:"scrap_reason" json:"scrap_reason"`
    ScrappedBy            int `db:"scrapped_by" json:"scrapped_by"`
}

func main() {
    router := gin.Default()

    opt := router.Group("opt/v2")
    {
        opt.GET("/last-completed-test/:serial", LastTest)
    }

    // Add API handlers here
    router.Run(":3000")
}

func LastTest(c *gin.Context) {
    // Connection to the database
    db := InitDB()
    defer db.Close()

    var result TestResult

    // get param and query
    //serial := c.Params.ByName("serial")

    db.Table("test_result").Where("serial = ?", "124111-0027").Scan(&result)

    if result.ID != 0 {
         //Display JSON result
        c.JSON(200, result)
    } else {
        // Display JSON error
        c.JSON(404, gin.H{"error": "Record not found", "code": 404})
    }
}

控制台输出:

[GIN-debug] Listening and serving HTTP on :3000 Successfully connected to MySQL[GIN] 2017/02/15 - 09:05:13 |[97;43m 404 [0m|      4.5005ms | 127.0.0.1 |[97;4 4m  [0m GET     /opt/v2/last-completed-test/124111-0027

网页输出:

{"id":2252920,"date_added":"0001-01-01T00:00:00Z","serial":"","sequence_id":0,"last_completed_stage":0,"last_completed_sequence":0,"workorder":"","product":"","is_complete":"","is_scrapped":"","value_stream":"","promise_date":"","fail_lock":0,"sequence_rev":0,"date_updated":"0001-01-01T00:00:00Z","date":"0001-01-01T00:00:00Z","time":"0001-01-01T00:00:00Z","ptyp2":"","wo_qty":0,"is_active":0,"is_time_lock":0,"time_lock_timestamp":"0001-01-01T00:00:00Z","scrap_reason":"","scrapped_by":0}

来自 Workbench 的架构:

在上面的代码中,我什至硬编码了一个序列号,我知道没有数据。

在尝试查询我的数据库时是否有明显的遗漏?

谢谢!

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    需要初始化结果变量,试试:

     db.Table("test_result").Where("serial = ?", "124111-0027").Scan(&result)
    

    【讨论】:

    • 我也试过这个,我做了你的改变,得到一个空的结果集。我将把上面的 JSON 返回放在我的问题中。
    • 我刚刚在返回的 JSON 中注意到一件有趣的事情,返回的 ID 是正确的,但是字段的结果没有返回???
    • TestResult 结构在上面的代码中靠近顶部。
    • 好的,我想我已经接近了,如果我注释掉所有其他字段的数据返回的所有日期字段。所以我假设我没有使用 time.Time 在 Golang 中正确表示 Date/DateTime/Timestamp 字段?
    • 你的数据库表有什么类型的字段?
    【解决方案2】:

    好的,问题出在 MySQL 日期/日期时间字段上,我没有传入

    ?charset=utf8&parseTime=True

    db, err := gorm.Open("mysql", "api:password@tcp(10.1.1.1:3306)/opt_db1?charset=utf8&parseTime=True")
    

    到数据库连接字符串。

    https://github.com/jinzhu/gorm/issues/56

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2012-06-14
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多