LoginSignup
0
0

Go: gorm で PostgreSQL のデータを更新 (Update)

Last updated at Posted at 2023-03-03

プログラム

フォルダー構造

$ tree -a
.
├── .env
├── config_postgres.go
└── gorm_pg_update.go
gorm_pg_update.go
// ----------------------------------------------------------------
//
//	gorm_pg_update.go
//
//					Mar/03/2023
//
// ----------------------------------------------------------------
package main

import (
	"fmt"
	"os"
	"strconv"
	"time"
	"gorm.io/gorm"
	"gorm.io/driver/postgres"
)

// ----------------------------------------------------------------
func main() {
	fmt.Fprintln (os.Stderr,"*** 開始 ***")
	key_in := os.Args[1]
	population_in,_ := strconv.Atoi (os.Args[2])

	fmt.Printf ("key_in = %s\t" , key_in)
	fmt.Printf ("population_in = %d\n" , population_in)

	host,user,password,data_base := config_postgres_proc()

dsn := "host=" + host + " user=" + user + " password=" + password + " dbname=" + data_base + " port=5432 sslmode=disable TimeZone=Asia/Tokyo"

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
		}

	today := get_current_date_proc ()

	fmt.Println (today)

	db.Exec("UPDATE cities SET population = ?,date_mod = ? WHERE id = ?", population_in,today,key_in)

	fmt.Fprintln (os.Stderr,"*** 終了 ***")
}

// ----------------------------------------------------------------
func get_current_date_proc () string {
	now := time.Now ()
	fmt.Printf ("%s\t" ,now)
	fmt.Printf ("%d-%d-%d\n" ,now.Year (),now.Month(),now.Day())
	today := strconv.Itoa (now.Year()) + "-" +
		fmt.Sprintf ("%d",now.Month()) + "-" +
		strconv.Itoa (now.Day())

	return	today
}

// ----------------------------------------------------------------

.env
config_postgres.go
はこちら
Go: gorm で PostgreSQL のバージョンを表示

実行の準備

go mod init update
go mod tidy

go.mod go.sum が作成される。

実行結果

$ go run gorm_pg_update.go config_postgres.go t3466 48532100
*** 開始 ***
key_in = t3466	population_in = 48532100
2023-03-03 17:38:09.509613607 +0900 JST m=+0.005400168	2023-3-3
2023-3-3
*** 終了 ***
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0