Home  >  Article  >  Backend Development  >  Query a database Using Go

Query a database Using Go

王林
王林Original
2024-08-16 07:06:42287browse

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.

The above is the detailed content of Query a database Using Go. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn