Welcome to our comprehensive guide on working with databases in Go using the sql.DB package! By the end of this lesson, you'll be able to connect to databases, execute queries, and handle results. Let's dive in! šÆ
In Go, the sql.DB package provides a simple interface to interact with various database management systems. It serves as a handle to establish and maintain connections with the database. š
Before we start, make sure you have Go installed on your machine. You can download it from official Go website.
Let's create a connection with a SQL database. We'll use PostgreSQL as our example database.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/lib/pq"
)
func main() {
const (
host = "localhost"
port = 5432
user = "your_user"
password = "your_password"
dbname = "your_db_name"
)
psqlInfo, err := sql.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname))
if err != nil {
log.Fatal(err)
}
defer psqlInfo.Close()
fmt.Println("Successfully connected to the database!")
}š Note: Replace your_user, your_password, and your_db_name with your actual PostgreSQL credentials.
Now that we have a connection, let's execute some queries and handle the results.
row := psqlInfo.QueryRow("SELECT COUNT(*) FROM users;")
var count int
row.Scan(&count)
fmt.Println("Total users:", count)In the above code snippet, we execute a query to count the number of users in the users table and print the result.
Prepared statements are precompiled SQL statements that can be used multiple times with different arguments. They offer better performance and security.
stmt, err := psqlInfo.Prepare("SELECT * FROM users WHERE id = $1;")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
result, err := stmt.Exec(userID)
if err != nil {
log.Fatal(err)
}
row = result.RowsAffected()In the above example, we prepare a statement to select all data for a specific user and execute it with the user's ID.
It's essential to handle errors when working with databases. Go provides the err variable to handle errors.
err := psqlInfo.Ping()
if err != nil {
log.Fatal(err)
}In the example above, we use the Ping method to check if the connection is alive and log an error if it's not.
What is the purpose of the `sql.DB` package in Go?
That's it for our introduction to the sql.DB package in Go! Practice these concepts and dive deeper into Go's database capabilities. Happy coding! š