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)
}
}
Comments
Post a Comment