doubinchou4219 2016-02-27 20:13
浏览 55
已采纳

尝试从模型创建表时出错

I started to play with gorm today but to bad came across some silly error and am stuck on it for a while. At first I am on windows and run MySQL 5 (5.0.51b) and latest version of go. I did go get for gorm and mysql driver and it compiles without an error and is able to connect (likely), but whenever I try to create a table based on declared type it throws an error which isn't informative (because the error is thrown by MySQL). Here is my code:

mport (
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
)

type User struct {
    id int
}

func main() {
    db, err := gorm.Open("mysql", "root:vertrigo@/shop?charset=utf8&parseTime=True&loc=Local")
    fmt.Println(err)

    a := db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&User{})

    fmt.Println(a)
}

So the model is aimed to be very basic, e.g. a table with one column. Now comes the output:

< nil > &{0x111e2230 Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ENGINE=InnoDB' at line 1 0 0x112d4060 0x112d4000 0x112d8140 0 {0x112a3f20} false map[gorm:table_options:ENGINE=InnoDB] map[]}

The first is a connection error which means it's able to connect but with the query it's not that good and the error says almost nothing other than SQL generated by gorm fails for some reason. So the question is if some one has an idea why the error is thrown and if there is any solution.

  • 写回答

1条回答 默认 最新

  • duanchen7703 2016-02-29 07:34
    关注

    That error occurs when trying to create an empty table, eg:

    create table User() ENGINE=InnoDB
    

    gorm generates an empty table statement because the id field of the User struct is private.

    Change id int to ID int. Capitalising the first letter of a struct field exposes it to external packages.


    As a secondary issue, instead of just printing the error:

    db, err := gorm.Open(...
    fmt.Println(err)
    

    it's a good idea to check every potential error, and deal with them immediately:

    db, err := gorm.Open(...
    if err != nil {
        log.Fatal(err)
    }
    

    For other errors, gorm's error handling is a little unusual compared to most go code. You'll probably want to frequently check for errors using db.GetErrors().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计