DEV Community

Sukma Rizki
Sukma Rizki

Posted on

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

Enter fullscreen mode Exit fullscreen mode

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)
    }
}

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)