プログラム
フォルダー構造
$ tree -a
.
├── .env
├── config_postgres.go
└─── gorm_pg_create.go
gorm_pg_create.go
// ----------------------------------------------------------------
//
// gorm_pg_create.go
//
// Mar/03/2023
//
// ----------------------------------------------------------------
package main
import (
"fmt"
"os"
"gorm.io/gorm"
"gorm.io/driver/postgres"
)
// ----------------------------------------------------------------
func unit_gen_proc (name string,population int,date_mod string) map[string]interface{} {
unit_aa := make (map[string]interface{})
unit_aa["name"] = name
unit_aa["population"] = population
unit_aa["date_mod"] = date_mod
return (unit_aa)
}
// ----------------------------------------------------------------
func data_prepare_proc () map[string](map[string]interface{}) {
dict_aa := make (map[string](map[string]interface{}))
dict_aa["t3461"] = unit_gen_proc ("広島",37452,"1921-11-11")
dict_aa["t3462"] = unit_gen_proc ("福山",89271,"1921-8-25")
dict_aa["t3463"] = unit_gen_proc ("東広島",63597,"1921-4-14")
dict_aa["t3464"] = unit_gen_proc ("呉",95178,"1921-2-20")
dict_aa["t3465"] = unit_gen_proc ("尾道",41749,"1921-6-24")
dict_aa["t3466"] = unit_gen_proc ("竹原",74582,"1921-1-10")
dict_aa["t3467"] = unit_gen_proc ("三次",48297,"1921-10-19")
dict_aa["t3468"] = unit_gen_proc ("大竹",38591,"1921-12-28")
dict_aa["t3469"] = unit_gen_proc ("府中",25978,"1921-5-14")
return (dict_aa)
}
// ----------------------------------------------------------------
func main() {
fmt.Fprintln (os.Stderr,"*** 開始 ***")
dict_aa := data_prepare_proc ()
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)
}
db.Exec ("drop table cities")
sql_str := "create table cities (id varchar(10),name varchar(20),population int,date_mod date)"
fmt.Println (sql_str)
db.Exec (sql_str)
for key,_ := range dict_aa {
name := dict_aa[key]["name"]
population := dict_aa[key]["population"]
date_mod := dict_aa[key]["date_mod"]
sql_str :="insert into cities (id,name,population,date_mod) values (?,?,?,?)"
db.Exec (sql_str,key,name,population,date_mod)
}
fmt.Fprintln (os.Stderr,"*** 終了 ***")
}
// ----------------------------------------------------------------
.env
config_postgres.go
はこちら
Go: gorm で PostgreSQL のバージョンを表示
実行の準備
go mod init create
go mod tidy
go.mod go.sum が作成される。
実行結果
$ go run gorm_pg_create.go config_postgres.go
*** 開始 ***
create table cities (id varchar(10),name varchar(20),population int,date_mod date)
*** 終了 ***
確認したバージョン
$ go version
go version go1.22.2 linux/amd64