what is database/sql in golang ?

The database/sql package in Golang provides a generic interface for working with relational databases. It allows Golang programs to connect to a wide range of SQL databases, including MySQL, PostgreSQL, SQLite, and others, using the same API.

The database/sql package provides a set of interfaces and functions that allow Golang programs to:

  • Open and close database connections
  • Prepare and execute SQL statements
  • Fetch and iterate over query results
  • Bind values to SQL queries
  • Manage transactions

Here's an example of using the database/sql package to query a MySQL database:

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()


    rows, err := db.Query("SELECT name, age FROM users WHERE age > ?", 18)

    if err != nil {

        panic(err.Error())

    }

    defer rows.Close()


    for rows.Next() {

        var name string

        var age int

        err = rows.Scan(&name, &age)

        if err != nil {

            panic(err.Error())

        }

        fmt.Printf("Name: %s, Age: %d\n", name, age)

    }

}


In this example, we import the database/sql package and the go-sql-driver/mysql package, which provides a MySQL driver for database/sql. We use the sql.Open function to open a connection to a MySQL database, passing in the connection string as a parameter. We then use the db.Query function to execute a SELECT query and retrieve the results as a set of rows. We use the rows.Next method to iterate over the rows, and the rows.Scan method to extract the values of the columns in each row. Finally, we print the results to the console.

Comments