Middle+
What tasks did you perform with databases?
sobes.tech AI
Answer from AI
In working with databases in Go, I usually perform the following tasks:
- Connecting to the database using drivers (e.g., database/sql with drivers for PostgreSQL, MySQL, etc.).
- Writing SQL queries, both directly and through ORM (e.g., GORM).
- Implementing transactions to ensure atomicity of operations.
- Optimizing queries and indexes to improve performance.
- Managing database schema migrations using tools like goose or sql-migrate.
- Working with context (context.Context) to control query execution time and cancellation.
Example of connecting and executing a simple query in Go:
import (
"database/sql"
_ "github.com/lib/pq"
"log"
)
func getUserName(db *sql.DB, userID int) (string, error) {
var name string
err := db.QueryRow("SELECT name FROM users WHERE id = $1", userID).Scan(&name)
if err != nil {
return "", err
}
return name, nil
}