반응형

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
반응형
type PostgerSQL struct {
    ConnectionString string
}

func (s *PostgerSQL) Init(e *EndPoint) {
    s.ConnectionString = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", e.PostgreSQL.Host, e.PostgreSQL.USER, e.PostgreSQL.PASSWORD, e.PostgreSQL.DATABASE)
}

func (s *PostgerSQL) Open() *sql.DB {
    db, err := sql.Open("postgres", s.ConnectionString)
    if err != nil {
        log.Panic().Stack().Err(err).Msg("Open")
    }
    db.SetMaxOpenConns(200)
    db.SetMaxIdleConns(2)
    return db
}

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

golang docker 말기  (0) 2022.11.24
golang 공유 자원 사용하기  (0) 2022.11.03
golnag으로 pg에 간단히 insert 하는 법  (0) 2022.11.02
postgresql wsl2에 설치  (0) 2022.10.26
vscode perfoce 플러그인 연동  (0) 2022.10.21
반응형
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