How to perform a SELECT query in Go to fetch data from an SQL database?

To perform a SELECT query in Go to fetch data from an SQL database, you can use the database/sql package along with the appropriate database driver. Here's an example:

  1. Install the required database driver:

    • For MySQL: go get github.com/go-sql-driver/mysql
    • For PostgreSQL: go get github.com/lib/pq
  2. Import the required packages:

import ( "database/sql" _ "github.com/go-sql-driver/mysql" // MySQL driver // _ "github.com/lib/pq" // PostgreSQL driver )
  1. Establish a database connection:
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") // db, err := sql.Open("postgres", "postgres://user:password@localhost/database?sslmode=disable") if err != nil { panic(err.Error()) } defer db.Close()
  1. Execute the SELECT query:
rows, err := db.Query("SELECT * FROM table_name") if err != nil { panic(err.Error()) } defer rows.Close()
  1. Iterate over the result set and handle the retrieved data:
for rows.Next() { var col1, col2 string if err := rows.Scan(&col1, &col2); err != nil { // Specify column types based on your table structure panic(err.Error()) } // Handle retrieved data fmt.Println(col1, col2) } if err := rows.Err(); err != nil { panic(err.Error()) }

That's it! This is a basic example of how to perform a SELECT query in Go to fetch data from an SQL database. Remember to modify the connection string (sql.Open()) and column types (rows.Scan()) according to your specific setup.