Connect to Postgresql with GO

Start Postgre with Docker


version: "3"
    image: postgres
    container_name: postgres
      - 5432:5432
      - POSTGRES_USER=root
      - POSTGRES_PASSWORD=password
    tty: true
    restart: always
    user: root
      - ./init:/docker-entrypoint-initdb.d
      - /etc/localtime:/etc/localtime:ro
    image: sosedoff/pgweb
    container_name: pgweb
      - "8081:8081"
      - DATABASE_URL=postgres://root:password@postgres:5432/testdb?sslmode=disable
      - postgres:postgres
    restart: always
      - postgres


docker-compose up -d

Connect from Go


package main

import (
    _ ""

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

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

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)

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

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

    // Create table.
    _, err = db.Exec("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
    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)
    _, err = db.Exec(sql_statement, "orange", 154)
    _, err = db.Exec(sql_statement, "apple", 100)
    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


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


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