Welcome to our deep dive into Go querying rows! In this lesson, we'll learn how to interact with databases and fetch data using Go, a powerful programming language for modern systems.
By the end of this lesson, you'll be able to:
Let's get started! ๐ฏ
Before we can query rows, we need to establish a connection to our database. In this example, we'll use MySQL, but the concepts apply to other databases as well.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database_name")
if err != nil {
panic(err)
}
defer db.Close()
fmt.Println("Connected to database!")
}๐ Note: Replace username, password, localhost, and database_name with your actual database credentials and details.
Now that we have a connection, let's learn how to query rows.
func main() {
// ... (existing code)
query := `SELECT id, name FROM users`
rows, err := db.Query(query)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id, name string
err = rows.Scan(&id, &name)
if err != nil {
panic(err)
}
fmt.Println(id, name)
}
}๐ Note: Replace users and the column names (id and name) with the actual table and column names from your database.
This code executes a SQL query, retrieves rows, and iterates through them. For each row, it assigns the column values to variables id and name.
Error handling is crucial when working with databases. In the example above, we've used the panic function to stop the execution when an error occurs. This is a drastic measure, and in a real-world application, you'd want to log the errors and handle them gracefully.
func main() {
// ... (existing code)
query := `SELECT id, name FROM users`
rows, err := db.Query(query)
if err != nil {
fmt.Println("Error querying rows:", err)
return
}
// ... (existing code)
}๐ Note: The fmt.Println function logs the error message, and return stops the execution of the function.
What's the purpose of the `defer` keyword in the `main` function's `rows` declaration?
Now you know how to connect to a database, query rows, and handle errors in Go. With this foundation, you can build powerful data-driven applications!
Keep exploring the Go documentation and practicing to master querying rows and other database operations. Happy coding! ๐กโจ