doujing5726 2019-04-05 14:26 采纳率: 0%
浏览 50

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

I use PostgresQL and Go. I have a table which is called 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). Can you help me with this?

This is a User struct in Go:

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:

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)

2nd example: I can pass first_name & email & username + full User object (postgres should update only these 3 fields)

I have tried to do it with map but I could not:

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

  }

  err := db.QueryRow(UPDATE "users" SET ())
}
  • 写回答

2条回答 默认 最新

  • duandao2083 2019-04-05 15:01
    关注

    Use UPDATE In the example i assume you have written the function, which takes variables. Lets assume the variables are:

    • firstName
    • lastName

    The SQL code is as follows:

    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

    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法