简体   繁体   English

如何使用Go函数更新PostgresQL表中的几列

[英]How to update several columns in PostgresQL table with a Go function

I use PostgresQL and Go. 我使用PostgresQL和Go。 I have a table which is called users . 我有一个称为users的表。 I try to write a function which will be able to update several columns. 我尝试编写一个能够更新几列的函数。 This function takes column names and user object (type struct). 此函数采用列名和用户对象(类型struct)。 Can you help me with this? 你能帮我吗?

This is a User struct in Go: 这是Go中的User结构:

type User struct {
  ID          int       json:"id"
  Username    string    json:"username"
  Password    string    json:"password"
  FirstName   string    json:"first_name"
  LastName    string    json:"last_name"
  Email       string    json:"email"
}

This is SQL script which creates users table: 这是创建用户表的SQL脚本:

create table "users"
(
  id                       serial       not null
  constraint user_pk
  primary key,
  username                 varchar(64)  not null,
  password                 varchar(128) not null,
  first_name               varchar(64)  not null,
  last_name                varchar(64)  not null,
  email                    varchar(64)  not null
);

1st example: I can pass first_name & last_name + full User object (postgres should update only these 2 fields) 第一个示例:我可以传递first_namelast_name +完整的User对象(postgres应该仅更新这两个字段)

2nd example: I can pass first_name & email & username + full User object (postgres should update only these 3 fields) 第二个示例:我可以传递first_nameemailusername +完整的User对象(postgres应该仅更新这3个字段)

I have tried to do it with map but I could not: 我试图用map来做,但是我做不到:

func UpdateUser(db *sql.DB, m map[string]interface{}) (*User, error) {
  for key, value := range m {

  }

  err := db.QueryRow(UPDATE "users" SET ())
}

Use UPDATE In the example i assume you have written the function, which takes variables. 使用UPDATE在示例中,我假设您已经编写了函数,该函数带有变量。 Lets assume the variables are: 假设变量为:

  • firstName 名字
  • lastName

The SQL code is as follows: SQL代码如下:

UPDATE users
SET first_name = firstName, last_name= lastName
WHERE [condition] 

You may find that you need to write a class for this with an overloaded constructor so that it takes any number of variables that you want. 您可能会发现您需要为此编写一个带有重载构造函数的类,以便它可以接收任意数量的所需变量。

Or better still write a function for each of the rows: 或者最好还是为每行写一个函数:

UPDATE users
SET first_name = firstName
WHERE [condition] 

UPDATE users
SET last_name= lastName
WHERE [condition]

etc. It just means that the user will have to enter the items one at a time. 等等。这只是意味着用户将不得不一次输入一个项目。

https://www.w3schools.com/sql/sql_update.asp https://www.w3schools.com/sql/sql_update.asp

Here's my user update func: 这是我的用户更新功能:

I pass a User struct to the function and don't worry about which fields need to be updated, I just update them all. 我将User结构传递给该函数,不用担心需要更新哪些字段,我只更新了所有字段。 The caller is working with a User they got from a previous func that returned it from the DB (I'll show you the API handler if you want to see that). 调用者正在与他们从数据库返回的前一个func中获得的User一起工作(如果您愿意的话,我将向您显示API处理程序)。

After the update I call the Get function to get the freshly updated record from the DB and return the User struct. 更新之后,我调用Get函数从数据库中获取新近更新的记录并返回User结构。 This is for certainty that the caller can see precisely what they just did. 可以肯定的是,呼叫者可以准确看到他们刚刚所做的事情。

// Update a User identified by id
func (u *UserModel) Update(user *models.User) (*models.User, error) {
    stmt := `UPDATE user SET
            first_name = ?,
            last_name = ?,
            email = ?,
            phone = ?,
            status_id = ?
        WHERE id = ?`

    var userStatus models.UserStatus
    userStatusID := userStatus.GetID(user.Status)

    _, err := u.DB.Exec(stmt, user.FirstName, user.LastName, user.Email, user.Phone, userStatusID, user.ID)
    if err != nil {
        if mysqlErr, ok := err.(*mysql.MySQLError); ok {
            if mysqlErr.Number == 1062 && strings.Contains(mysqlErr.Message, "uk_user_email") {
                return nil, models.ErrDuplicateEmail
            }
        }
        return nil, err
    }

    user, err = u.Get(int(user.ID))
    if err != nil {
        return nil, err
    }

    return user, nil
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM