👨‍💻
Dokumentasi Golang (PT Phincon)
  • 🚀Dokumentasi Bootcamp (PT Phincon)
  • Command di Golang
  • Static Type di Golang
  • Variable and Constant
    • Variable daI Constant
    • Deklarasi Variabel
    • Iota (Auto Increment)
    • Blank Identifier (Variable Underscore)
    • Access Modifier (Public or Private)
  • Tipe Data Primitif
    • Integer dan Unsigned Integer
    • Float dan Complex
    • String
    • Boolean
  • Tipe Data Aggregate
    • Array
    • Struct
  • Tipe Data Reference
    • Slice
    • Map
    • Function in Golang
      • Function
      • Function vs Method
      • Function vs Procedure
      • Private vs Public Function
      • Function Init dan Main
      • Function dengan Return Multiple Value
      • Variadic Function
      • Function sebagai Parameter
      • Anonymous Function
      • Input Function dari CLI
      • Exercise (Function)
  • Default Value setiap Tipe Data
  • Type Declaration di Golang
    • Type Declaration
    • Type Declaration Built-In di Golang
  • Kebab Case, Camel Case, Snake Case & Pascal Case di Golang
  • Konversi Tipe Data
  • If-Else dan Switch
    • If Else
    • Switch
    • Exercise
  • Looping
    • Looping For
    • Looping for range
    • Infinite Looping
    • Penerapan Looping pada Sorting
  • Operator di Golang
    • Arithmetic Operator
    • Assignment Operator
    • Relational Operator
    • Logic Operator
  • Interface
  • Interface Kosong atau Any
  • Nil
  • Pointer
    • Pass By Value dan Pass By Reference
    • Pointer (Pass By Reference)
    • Operator Address (& dan *)
    • Default Value Pointer
    • Tricky Case
    • Pointer pada Parameter di Function
    • Pointer pada Method
  • Package
    • Fmt
    • Rand
    • Os
    • Strings
      • To Lower
      • Contains
      • Split
      • Trim
      • Atoi
      • Itoa
      • EqualFold
    • Random Generator
    • Time
      • Get Current Time By Location
      • Time Sleep
      • Time Since
      • Timer & After
      • AfterFunc
      • Ticker & Tick
  • Go dan JSON
    • JSON vs XML
    • Unmarshal vs Marshal
    • Marshal (Go Object -> JSON)
    • Unmarshal (JSON -> Go Object)
    • Streaming Decoder & Encoder
    • Tag
    • JSON Go Return Byte
  • Go dan CSV
    • Insert Data ke File CSV
    • Insert 1.000.000 Data ke File CSV
  • Goroutine
    • Concurrency vs Parrarel
    • Go Routine Sederhana
    • Go Routine vs Synchronous
    • Wait Group
    • Defer
    • Channel
    • Buffered Channel
    • Select Channel
    • Deadlock - All goroutines are asleep
    • Race Condition
    • Mutex (Mutual Exclusion)
    • RW Mutex vs Mutex
    • Once
    • Pool
    • Atomic
    • Go Max Procs
    • Exit
    • Exercise 1 : Go Routine + Context + Channel
    • Exercise 2 : Worker (Go Routine + Channel + Context)
    • Exercise 3 : Random Worker (Go Routine + Channel + Context)
    • Exercise : Implementasi Goroutine dan Channel pada File CSV
  • Go Context
    • Pengenalan Context
    • Context Background & TODO
    • Context With Value
    • Context WithDeadline dan Context WithTimeout
    • Context WithCancel dan Context Done
  • Pengenalan HTTP
  • Go Native HTTP
    • HTTP Server
    • HTTP Server Multi Handler
    • HTTP Server dengan Serve Mux
    • HTTP Response Writer
    • HTTP Test
    • Routing
    • Konsep Middleware
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
    • Hit Endpoint dengan Curl di Terminal
  • Go Gin Framework
    • HTTP Server
    • Router
    • Middleware
    • Get Query Parameter
    • Get Path Parameter
    • Request JSON
    • Request Form
    • Get dan Set Header
    • Get dan Set Cookie
    • Redirect
    • Serve File
    • Upload File
    • Download File
  • Golang dan Database
    • Instalasi MySQL dengan Docker Desktop
    • Instalasi PostgreSQL dengan Docker
    • Basic SQL
    • SQL Join
    • SQL Relation
    • Golang Database Driver
    • Golang dan SQL
  • Go Unit Test
    • Method di Package Testing
    • Package Assert & Require
    • Running Sub Test
    • Table Test
    • Generate Coverage Unit Testing dalam Bentuk HTML
  • Sonar Qube dan Sonar Scanner
  • Logging
  • Golang dan Redis
  • Golang dan RabbitMQ
    • Instalasi RabbitMQ dengan Docker
    • Instalasi Package RabbitMQ di Golang
    • Publisher dan Consumer
    • Publisher dan Multi Consumer
    • Setting RabbitMQ (Durable, Auto Delete dan Ack)
  • Git Command
  • Git Clone dengan SSH
  • Anotasi dan Package di Java Spring Boot
Powered by GitBook
On this page
  • SQL Query di Golang dengan Query Parameter
  • Prepare Statement
  • Database Transaction
  • Implementasi Query Parameter, Prepare Statement dan Database Transaction pada Insert Data ke Database
  • Link Code
  1. Golang dan Database

Golang dan SQL

SQL Query di Golang dengan Query Parameter

Tujuan adanya query parameter adalah untuk menghindari SQL injection. Jika menggunakan MySQL, query parameter dapat disisipkan di query dengan tanda ?. Lalu value di query dapat di input melalui fungsi ExecContext() untuk query Insert, Update dan Delete atau fungsi QueryContext() untuk query Get seperti code di bawah ini.

insert into comments (email, comment) value (?,?)
update contact SET name = ?, no_telp = ? where id = ?
delete FROM contact where id = ?

Jika menggunakan pgx (driver golang PostgreSQL), query parameter disisipkan di query dengan tanda $1, $2 dan seterusnya sesuai urutan parameter.

insert into comments (email, comment) value ($1,$2)
update contact SET name = $1, no_telp = $2 where id = $3
delete FROM contact where id = $1

Prepare Statement

Prepare statement digunakan untuk memastikan query yang di eksekusi berada dalam 1 koneksi database yang sama.

Database Transaction

Database transaction digunakan supaya SQL yang dikirim tidak langsung di commit ke database. Implementasi database transaction semisal jika kita ingin melakukan insert beberapa database, lalu ada 1 data yang gagal di create. Maka kita bisa menggunakan database transaction untuk me-rollback atau membatalkan create seluruh data yang telah di insert ke database. Database transaction di awali dengan inisiasi berikut.

trx, err := db.BeginTx(ctx, nil)
if err != nil {
	panic(err) // bisa diganti dengan fmt atau log
}

Query dapat di commit dengan code berikut.

trx.Commit()

Namun, ada kalanya ingin dilakukan pengecekan untuk menghindari error. Jika error terjadi dapat di atasi dengan code berikut.

if err != nil {
    trx.Rollbacck()
}

Implementasi Query Parameter, Prepare Statement dan Database Transaction pada Insert Data ke Database

Catatan : untuk query get seluruh data, update dan delete 1 data tidak memerlukan prepare statement ataupun database transaction.

main.go
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/jackc/pgx/v5/stdlib"
)

var listItem = map[string]float64{
	"item1": 40000,
	"item2": 30000,
	"item3": 50000,
}

func main() {
	db := GetDBConnection("pgx")
	InsertPostgreSQL(db)
}

func GetDBConnection(driver string) (db *sql.DB) {
	var connString string
	if driver == "mysql" {
		// "username:password@tcp(host:port)/database_name"
		connString = fmt.Sprintf("%s:%s@tcp(%s:%d)/%v",
			"root", "@Ugm428660", "localhost", 3306, "bootcamp")
	} else if driver == "pgx" {
		// "postgres://username:password@localhost:5432/database_name"
		connString = fmt.Sprintf("postgres://%s:%s@%s:%d/%s",
			"postgres", "@Ugm428660", "localhost", 5432, "postgres")
	}

	db, err := sql.Open(driver, connString)
	if err != nil {
		panic(err)
	}
	log.Printf("Running database")

	db.SetMaxIdleConns(2)
	db.SetMaxOpenConns(5)
	db.SetConnMaxIdleTime(10 * time.Minute)
	db.SetConnMaxLifetime(60 * time.Minute)
	return
}

func InsertPostgreSQL(db *sql.DB) {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	// query parameter -> to prevent SQL Injection
	query := `insert into product (name, price) values ($1, $2)`
	// database transaction
	trx, err := db.Begin()
	if err != nil {
		panic(err)
	}
	
	// prepare statement 
	preparestmt, err := trx.PrepareContext(ctx, query)
	if err != nil {
		panic(err)
	}

	for i, v := range listItem {
		res, err := preparestmt.ExecContext(ctx, i, v)
		if err != nil {
			trx.Rollback()
			panic(err)
		}

		// LastInsertId is not supported by this driver
		lastInsertedID, err := res.LastInsertId()
		rowAffected, _ := res.RowsAffected()
		fmt.Printf("(%d, %d)", lastInsertedID, rowAffected)
	}
	trx.Commit()

	defer db.Close()
}

Link Code

Berikut contoh code penerapan query parameter, prepare statement dan database transaction di Golang.

PreviousGolang Database DriverNextGo Unit Test

Last updated 1 year ago

Logocontact-go/repository/contact_http_db_impl.go at master · rafli-ramadhan/contact-goGitHub
Logosales-go/repository at master · rafli-ramadhan/sales-goGitHub