我是个新人,我正在努力寻找建立我的数据库交流的最佳方式.基本上,我记得在我以前的工作中,您可以在PHP中创建一个表示SQL表的类,当您需要将数据插入到数据库中时,您可以创建一个包含所有必要数据的类的对象,调用Insert(),传递您的对象,它会将数据插入到相应的表中,而不需要编写任何SQL代码,UPDATE()的工作方式非常相似,不同之处在于它将更新而不是插入.不幸的是,我不记得那个PHP框架的名字了,但也许有人知道在Go中实现这样的东西的方法,或者它不是一件事?

假设我有一个 struct :

type Patients struct {
    ID              int
    Name            string 
    Image           string    
}

现在,我想要有一个函数,它以Patients Objet为参数,并将其插入到Patients Postgres表中,自动将Patients转换为Postgres期望的值:

func (patients *Patients) insert(patient Patients) {

}

然后update()将获取一个Patients对象,基本上执行这段代码,而不需要我编写它:

stmt := `update patients set
    name = $1,
    image = $2,
    where id = $3
`

_, err := db.ExecContext(ctx, stmt,
    patient.Name,
    patient.Image,
    patient.ID
)

推荐答案

您正在寻找一种称为ORM(对象关系映射器)的东西.有一些围棋,但最受欢迎的是GORM.这是一个有点有争议的话题,但我认为如果您是Go和/或数据库的新手,使用ORM是一个好主意.这将为你节省大量的时间和精力.

另一种方法是使用数据库/SQL包并编写您自己的SQL查询.如果您是一名经验丰富的围棋开发人员和/或数据库管理员,这是一个好主意.它将使您能够更好地控制您的查询,并将更加高效.推荐读数:https://www.alexedwards.net/blog/organising-database-access.此方法建议使用的库包括SQLx和PGx.

下面是作为GORM模型的 struct :

type Patient struct {
    ID              int `gorm:"primaryKey"`
    Name            string 
    Image           string    
}

下面是一个如何将患者插入数据库的示 routine 序:

package main

import (
    "fmt"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Patient struct {
    ID              int `gorm:"primaryKey"`
    Name            string 
    Image           string    
}

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable TimeZone=UTC"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    db.AutoMigrate(&Patient{})

    patient := Patient{
        Name: "John Smith",
        Image: "https://example.com/image.png",
    }

    result := db.Create(&patient)
    if result.Error != nil {
        panic(result.Error)
    }

    fmt.Println(patient)
}

如果您想要使用SQLX,您可以编写如下代码:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

type Patient struct {
    ID              int
    Name            string 
    Image           string    
}

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable TimeZone=UTC"
    db, err := sql.Open("postgres", dsn)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    _, err = db.Exec(`
        CREATE TABLE IF NOT EXISTS patients (
            id SERIAL PRIMARY KEY,
            name TEXT,
            image TEXT
        )
    `)
    if err != nil {
        log.Fatal(err)
    }

    patient := Patient{
        Name: "John Smith",
        Image: "https://example.com/image.png",
    }

    _, err = db.Exec(`
        INSERT INTO patients (name, image) VALUES ($1, $2)
    `, patient.Name, patient.Image)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(patient)
}

当然,使用ORM管理数据库模式会稍微复杂一些.您可以使用迁移,但我更喜欢使用名为GOOSE的工具.设置它有点麻烦,但它非常强大和灵活.下面是一个如何使用它的示例:

package main

import (
    "fmt"
    "log"

    "github.com/pressly/goose"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Patient struct {
    ID              int `gorm:"primaryKey"`
    Name            string 
    Image           string    
}

func main() {
    dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable TimeZone=UTC"
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    goose.SetDialect("postgres")
    goose.SetTableName("schema_migrations")

    err = goose.Run("up", db.DB(), "migrations")
    if err != nil {
        log.Fatal(err)
    }

    patient := Patient{
        Name: "John Smith",
        Image: "https://example.com/image.png",
    }

    result := db.Create(&patient)
    if result.Error != nil {
        panic(result.Error)
    }

    fmt.Println(patient)
}

其中您的迁移目录如下所示:

migrations/
    00001_create_patients.up.sql
    00001_create_patients.down.sql

您的迁移如下所示:

-- 00001_create_patients.up.sql
CREATE TABLE patients (
    id SERIAL PRIMARY KEY,
    name TEXT,
    image TEXT
);
-- 00001_create_patients.down.sql
DROP TABLE patients;

我希望这能帮到你!如果你有什么问题就告诉我.

Postgresql相关问答推荐

"错误:无法创建用户:错误:关系\users\违反了非空约束

使用函数返回值作为另一个函数的参数

是否可以在psql查询输出中删除新行末尾的+号?

如何使用 Grafana 测量 PostgreSQL 中的复制

对 Postgres 进行身份验证时如何使用自定义密码哈希算法?

Postgres内部如何计算月份间隔

使用 postgresql Select 整数作为位和状态表

postgreSQL 中对 utf-8 的 LC_COLLATE 和 LC_CTYPE 支持

在 PostgreSQL 中将时间转换为秒

如何使 Java 和 Postgres 枚举一起工作以进行更新?

从 PostgreSQL 中的字段中提取数字

获取 PostgreSQL 中当前正在运行的查询的参数

如何使用 postgresql 中的存储过程将数据插入表中

用于更改 postgresql 用户密码的 bash 脚本

子查询的自连接

在 PostgreSQL 中使用 Cursors进行分页

什么是 Postgres session?

查询 JSON 列中的数组元素

如何使用 PostgreSQL 在任何列中查找所有具有 NULL 值的行

Ruby 中 DateTime 的毫秒分辨率