Connect to Postgresql with GO

Start Postgre with Docker

docker-compose.yml


version: "3"
services:
  postgres:
    image: postgres
    container_name: postgres
    ports:
      - 5432: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

Start-up

docker-compose up -d

Connect from Go

main.go


package main

import (
    "database/sql"
    "fmt"
    _ "github.com/lib/pq"
)

const (
    // Initialize connection constants.
    HOST     = "127.0.0.1"
    DATABASE = "testdb"
    USER     = "root"
    PASSWORD = "password"
)

func checkError(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {
    // Initialize connection string.
    var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", HOST, USER, PASSWORD, DATABASE)

    // Initialize connection object.
    db, err := sql.Open("postgres", connectionString)
    checkError(err)

    err = db.Ping()
    checkError(err)
    fmt.Println("Successfully created connection to database")

    // Drop previous table of same name if one exists.
    _, err = db.Exec("DROP TABLE IF EXISTS inventory;")
    checkError(err)
    fmt.Println("Finished dropping table (if existed)")

    // Create table.
    _, err = db.Exec("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
    checkError(err)
    fmt.Println("Finished creating table")

    // Insert some data into table.
    sql_statement := "INSERT INTO inventory (name, quantity) VALUES ($1, $2);"
    _, err = db.Exec(sql_statement, "banana", 150)
    checkError(err)
    _, err = db.Exec(sql_statement, "orange", 154)
    checkError(err)
    _, err = db.Exec(sql_statement, "apple", 100)
    checkError(err)
    fmt.Println("Inserted 3 rows of data")
}
go run main.go

Connect with psql

Connect from shell

psql -h localhost -U root -d postgres -p 5432

DB list display

\l

Connect to the target DB

\c testdb

Check the current DB

select current_database();

Check if data is included

testdb=# select * from inventory;
 id |  name  | quantity 
----+--------+----------
  1 | banana |      150
  2 | orange |      154
  3 | apple  |      100

reference

https://qiita.com/hiro9/items/e6e41ec822a7077c3568 https://docs.microsoft.com/ja-jp/azure/postgresql/connect-go

Recommended Posts

Connect to Postgresql with GO
Connect to Wikipedia with Python
Connect to multiple databases with SQLAlchemy
Connect to Bitcoin Testnet with Pycoin
Connect to Elastic MQ with boto
Python with Go
Connect to MySQL with Python within Docker
Connect to GNU / Linux with Remote Desktop
Connect to mysql
Connect to s3 with AWS Lambda Python
Connect to pepper with PEPPER Mac's python interpreter
AtCoder Green tried to solve with Go
[Go] Use Open ID Connect with go-oidc
How to use SQLAlchemy / Connect with aiomysql
I want to connect to PostgreSQL from various languages
Easily connect Xillybus to user logic with cReComp
Connect to MySQL with Python on Raspberry Pi
Convert 202003 to 2020-03 with pandas
Connect python to mysql
How to make an HTTPS server with Go / Gin
I wrote you to watch the signal with Go
Draw Bezier curves with Go
Convert Select query obtained from Postgre with Go to JSON
Operate Db2 container with Go
Getting Started with Go Assembly
Post to slack with Python 3
Bit full search with Go
Scraping Go To Travel Accommodation
Output to syslog with Loguru
Introduction to RDB with sqlalchemy Ⅰ
Hot reload with Go + Air
Easy to make with syntax
How to update with SQLAlchemy?
Connect Vagrant's MySQL with MySQL Workbench
To run gym_torcs with ubutnu16
How to cast with Theano
How to connect to Cloud SQL PostgreSQL on Google Cloud Platform from a local environment with Java
How to define Go variables
[Go] How to use "... (3 periods)"
How to Alter with SQLAlchemy?
Connect to sqlite from python
Switch python to 2.7 with alternatives
Write to csv with Python
Try implementing perfume with Go
Connect to centos6 on virtualbox with ssh connection from Mac
How to separate strings with','
Connect the Jupyter Notebook kernel to Spyder with Jupytext enabled
Connect to s3 tokyo region
How to RDP with Fedora31
2 ways to deal with SessionNotCreatedException
How to Delete with SQLAlchemy?
Connect Raspberry Pi to Alibaba Cloud IoT Platform with Python
Make it possible to output a log to a file with go echo
How to connect to Cloud Firestore from Google Cloud Functions with python code
I tried to make a mechanism of exclusive control with Go
Convert .ipynb to .html (with BatchFile)
Learn algorithms with Go @ recursive call
How to cancel RT with tweepy
Steps to develop Django with VSCode
Python: How to use async with
Link to get started with python