Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Go Lang - Database Access

Accessing Databases in Go

Accessing databases in Go involves using database drivers and libraries to connect, query, and manipulate data in various database systems such as MySQL, PostgreSQL, and SQLite. Go provides excellent support for database operations with libraries like database/sql and ORMs such as GORM.

Key Points:

  • Go's database/sql package provides a lightweight and efficient interface for SQL databases.
  • ORMs (Object-Relational Mappers) like GORM simplify database interactions by mapping Go structs to database tables.
  • Using database/sql and ORMs allows developers to perform CRUD operations, transactions, and handle database-specific features.

Example of Database Access in Go

Below is an example demonstrating how to perform basic database operations using database/sql in Go:


// Example: Database access in Go
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // Connect to the MySQL database
    db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database_name")
    if err != nil {
        fmt.Println("Error connecting to database:", err)
        return
    }
    defer db.Close()

    // Perform a query
    rows, err := db.Query("SELECT id, name FROM users")
    if err != nil {
        fmt.Println("Error querying database:", err)
        return
    }
    defer rows.Close()

    // Iterate over the results
    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            fmt.Println("Error scanning row:", err)
            return
        }
        fmt.Println("ID:", id, "Name:", name)
    }

    // Check for errors during iteration
    if err := rows.Err(); err != nil {
        fmt.Println("Error iterating over rows:", err)
        return
    }
}
          

Summary

This guide provided an overview of accessing databases in Go, including examples of using database/sql for basic database operations. By leveraging Go's database capabilities, developers can efficiently connect to and interact with various databases to build robust applications.