반응형

https://stackoverflow.com/questions/2944297/postgresql-function-for-last-inserted-id

 

PostgreSQL function for last inserted ID

In PostgreSQL, how do I get the last id inserted into a table? In MS SQL there is SCOPE_IDENTITY(). Please do not advise me to use something like this: select max(id) from table

stackoverflow.com

  INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
  SELECT currval('persons_id_seq')
  INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
  SELECT currval(pg_get_serial_sequence('persons','id'));

'프로그래밍' 카테고리의 다른 글

wsl2 고정 ip처럼 사용하기  (0) 2022.12.06
docker network mode  (0) 2022.12.06
이번에 작업한 도커파일  (0) 2022.11.28
golang docker 말기  (0) 2022.11.24
golang 공유 자원 사용하기  (0) 2022.11.03
반응형
func (a *Account) Insert(db *sql.DB) {
    now := time.Now()
    sql_statement := "INSERT INTO account (account_id, device_model, memory_size, created_at) VALUES ($1, $2, $3, $4);"
    _, err := db.Exec(sql_statement, a.AccountId, a.DeviecModel, a.MemorySize, now)
    if err != nil {
        sql_statement = "UPDATE account SET device_model = $1, memory_size = $2, created_at = $3 WHERE account_id = $4;"
        result, _ := db.Exec(sql_statement, a.DeviecModel, a.MemorySize, now, a.AccountId)

        row, err := result.RowsAffected()

        if row == 0 || err != nil {
            log.Panic().Stack().Err(err).Msg("Insert")
        }
    }
}

+ Recent posts