DEV Community

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

Posted on

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.

Top comments (0)