package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/mydatabase") if err != nil { panic(err.Error()) } defer db.Close() var name string var age int err = db.QueryRow("SELECT name, age FROM users WHERE id = ?", 123).Scan(&name, &age) if err != nil { panic(err.Error()) } fmt.Printf("Name: %s\nAge: %d\n", name, age) }
package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "user=postgres password=secret dbname=mydatabase sslmode=disable") if err != nil { panic(err.Error()) } defer db.Close() var count int err = db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count) if err != nil { panic(err.Error()) } fmt.Printf("There are %d users in the database\n", count) }In this example, a connection is established to a PostgreSQL database and a query is executed to retrieve the total number of users in the database. The result is scanned into a variable and printed to the console. Both examples use the database/sql package and a specific driver package (either "github.com/go-sql-driver/mysql" or "github.com/lib/pq", depending on the database being used) to interact with the respective databases.