douju9272 2019-09-11 15:48
浏览 103

从sqlite3数据库和模型struct标记读取表时出现问题

I'm trying to implement a function in Go where I need to connect to a sqlite database. This DB has more than one model, and a superior suggested me using the GORM lib. It seems the program detects by name the table I'm attempting to access, but it always returns zero values (numerical attributes) or empty strings.

My first attempt was modelling the schema wihout struct tags, however it was the first time I got the problem. Then I tried using struct tags using the 'db' preffix, specifying the name of every attribute in SQLITE, but nothing changed. After that, I applied struct tags with the 'sql' preffix... Again nothing happened, and got the same problem. As a last attempt I changed the preffix to 'gorm', but got the problem once more. Afterwards, I deleted all the struct tags and left just the struct tag corresponding to the primary key (ID).

I don know what to do but to give GORM up and use another library... :(

The schema in SQLite

TABLE COMPANIES(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

The model I coded

type Company struct {
    gorm.Model
    ID      int `gorm:"PRIMARY_KEY"`
    Name    string
    Age     int
    Address string
    Salary  float32
}
fmt.Println(db.HasTable("COMPANIES"))//It returns "true"
db.First(&company) 
fmt.Println(company)

What is printed in console:

{{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} 0  0  0}

[2019-09-11 11:49:09]  no such column: companies.deleted_at 

The weird thing is, the table is actually populated, and has neither zero values nor empty strings.

  • 写回答

2条回答 默认 最新

  • duanben1324 2019-09-12 20:56
    关注

    At the end, I could solve my problem without specifying tags AND deleting the "gorm.Model" line. I had to implement the function "TableName" to indicate which table I want to read. Here's the code:

    package main

    import (
        "fmt"
    
        "github.com/jinzhu/gorm"
        _ "github.com/mattn/go-sqlite3"
    )
    
    type Company struct {
        ID      int     //`sql:"type: int;primary key; not null"`
        Name    string  //`sql:"type:text; not null "`
        Age     int     //`sql:"type: int; not null"`
        Address string  //`sql:"type: char(50)"`
        Salary  float32 //`sql:"type: real"`
    }
    
    func (Company) TableName() string {
        return "COMPANY"
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器