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:
Install the required database driver:
go get github.com/go-sql-driver/mysql
go get github.com/lib/pq
Import the required packages:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" // MySQL driver
// _ "github.com/lib/pq" // PostgreSQL driver
)
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()
rows, err := db.Query("SELECT * FROM table_name")
if err != nil {
panic(err.Error())
}
defer rows.Close()
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.