30
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go PostgreSQLにつないでみる

Posted at

PostgreSQLを用意する

docker-compose.yml
version: "3"
services:
  postgres:
    image: postgres
    container_name: postgres
    ports:
      - 5555:5432
    environment:
      - POSTGRES_USER=root
      - POSTGRES_PASSWORD=password
    tty: true
    restart: always
    user: root
    volumes:
      - ./init:/docker-entrypoint-initdb.d
      - /etc/localtime:/etc/localtime:ro
  pgweb:
    image: sosedoff/pgweb
    container_name: pgweb
    ports: 
      - "8081:8081"
    environment:
      - DATABASE_URL=postgres://root:password@postgres:5432/testdb?sslmode=disable
    links: 
      - postgres:postgres
    restart: always
    depends_on:
      - postgres
  • docker-compose up -d後に、http://localhost:8081pgwebに接続可能

capture.PNG

PostgreSQLにつないでみる

  • ソースコード
main.go
package main

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
)

type EMPLOYEE struct {
	ID     string
	NUMBER string
}

func main() {
	db, err := sql.Open("postgres", "host=127.0.0.1 port=5555 user=root password=password dbname=testdb sslmode=disable")
	defer db.Close()

	if err != nil {
		fmt.Println(err)
	}

	// INSERT
	var empID string
	id := 3
	number := 4444
	err = db.QueryRow("INSERT INTO employee(emp_id, emp_number) VALUES($1,$2) RETURNING emp_id", id, number).Scan(&empID)

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(empID)

	// SELECT
	rows, err := db.Query("SELECT * FROM employee")

	if err != nil {
		fmt.Println(err)
	}

	var es []EMPLOYEE
	for rows.Next() {
		var e EMPLOYEE
		rows.Scan(&e.ID, &e.NUMBER)
		es = append(es, e)
	}
	fmt.Printf("%v", es)
}
  • PostgreSQL用のドライバをインストール
    • go get github.com/lib/pq
  • 実行
    • go run main.go
    • 連続実行する場合は、INSERTを適宜見直す
  • 確認
    • コンソール出力とpgweb

参考

30
37
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
30
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?