import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func main() { // open a connection to the database db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") if err != nil { log.Fatal(err) } defer db.Close() // execute a query rows, err := db.Query("SELECT name, age FROM users") if err != nil { log.Fatal(err) } defer rows.Close() // read the results for rows.Next() { var name string var age int err := rows.Scan(&name, &age) if err != nil { log.Fatal(err) } fmt.Printf("%s is %d years old\n", name, age) } }
import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func main() { // open a connection to the database db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") if err != nil { log.Fatal(err) } defer db.Close() // prepare a statement stmt, err := db.Prepare("INSERT INTO users (name, age) VALUES (?, ?)") if err != nil { log.Fatal(err) } defer stmt.Close() // execute the statement with different parameters _, err = stmt.Exec("Alice", 20) if err != nil { log.Fatal(err) } _, err = stmt.Exec("Bob", 25) if err != nil { log.Fatal(err) } fmt.Println("Inserted two rows") }In this example, we use the sql.Prepare function to create a prepared statement that inserts a new row into a table. We then execute the statement twice with different parameters using stmt.Exec. This is more efficient than creating a new SQL string for each query. The package library used in both examples is the standard database/sql package.