"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Query a database Using Go

Query a database Using Go

Published on 2024-08-16
Browse:542

Query a database Using Go

Step 1: Install the MySQL driver
First, you'll need to install a MySQL driver for Go. A popular one is go-sql-driver/mysql. You can install it using:

go get -u github.com/go-sql-driver/mysql

Step 2: Write the Go code
Here’s an example of how you can connect to a MySQL database and query data:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // Open the database connection
    db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/dbname")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    // Ping the database to check if the connection is alive
    if err := db.Ping(); err != nil {
        log.Fatal(err)
    }

    // Define the query
    query := "SELECT id, name FROM users WHERE active = ?"
    active := true

    // Execute the query
    rows, err := db.Query(query, active)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    // Iterate through the result set
    for rows.Next() {
        var id int
        var name string
        if err := rows.Scan(&id, &name); err != nil {
            log.Fatal(err)
        }
        fmt.Printf("ID: %d, Name: %s\n", id, name)
    }

    // Check for errors from iterating over rows
    if err := rows.Err(); err != nil {
        log.Fatal(err)
    }
}

Explanation:
Import necessary packages: You import the database/sql package for database interactions and the MySQL driver (github.com/go-sql-driver/mysql).

Open the database connection: You open a connection to the database using sql.Open. The connection string format is username:password@tcp(host:port)/dbname.

Ping the database: It’s a good practice to ping the database to ensure that the connection is established.

Execute the query: You execute a query using db.Query. The Query method returns a *sql.Rows object, which you can iterate over to get the result set.

Iterate through the results: You use a loop to iterate through the rows and Scan each row into variables.

Handle errors: You should handle any errors that occur during the execution of the query or during iteration.

Step 3: Run your code
Make sure to replace username, password, 127.0.0.1:3306, and dbname with your actual MySQL credentials and database details.

Run your Go program, and it should output the results of your query.

This example can be adapted for other databases by changing the driver and connection string accordingly.

Release Statement This article is reproduced at: https://dev.to/sukmarizki04/query-a-database-using-go-5f41?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3