DEV Community

Cover image for BASIC POSTGRESQL APPLICATION VIA GOLANG
Murat Tunç
Murat Tunç

Posted on

2 1

BASIC POSTGRESQL APPLICATION VIA GOLANG

BASIC POSTGRESQL APPLICATION VIA GOLANG

In this study, I will try to introduce the simplest postgreSQL applicaiton using the Golang programming language. Intermediate level knowledge of Golang language will be sufficient.

Working environment

  • Debian Operating System
  • Golang sw language
  • PostgreSQL
  • DBeaver
  • VS Code

General hierarchy of the project

Image description

Dbeaver database table creation

Step 1

Image description

Step 2

Image description

Step 3

Image description

Step 4

Image description

Step 5

Image description

Step 6

Image description

Step 7

Image description

Step 8

Image description

Step 9

Image description

Step 10

Image description

Step 11

Image description

Step 12

Image description

Step 13

Image description

Now our Database table is ready !
Lets insert some values to it via Golang.

VS code

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/lib/pq"
)

const (
    user     = "postgres"
    password = "1234"
    dbname   = "postgres"
    host     = "localhost"
    port     = 5432
)

func main() {
    // Connection to database
    psqlconn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
    // Open the database
    db, err := sql.Open("postgres", psqlconn)
    if err != nil {
        panic(err)
    }
    fmt.Println("Database Connected!")
    // Close the database
    defer db.Close()
    insert := `insert into "icecream"("Name", "Price") values($1, $2)`
    // insert new raw to database table
    _, err = db.Exec(insert, "Vanilla", 4)
    if err != nil {
        panic(err)
    }
    _, err = db.Exec(insert, "Chocolate", 5)
    if err != nil {
        panic(err)
    }
    fmt.Println("Writing to database completed!")
}
Enter fullscreen mode Exit fullscreen mode

Run go file

Image description

Database table result

Image description

Github source code

github_source_code

I wish you good coding, thinking that it is educational and fun.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more