Working with Databases in Go – GORM and SQL Connections
Using database/sql Directly
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
defer db.Close()
rows, err := db.Query("SELECT id, name FROM users")
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
fmt.Println(id, name)
}
Using GORM (ORM Library)
GORM simplifies database interactions with struct-based models instead of raw SQL.
type User struct {
ID uint
Name string
}
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
db.Create(&User{Name: "Alice"})
var users []User
db.Find(&users)
Choosing Between Them
database/sql gives full control and is dependency-free, while GORM speeds up development with automatic migrations, associations, and query building at the cost of some added abstraction.
PreviousTesting in Go – Writing Unit Tests and Benchmarks (Table-Driven)
Next Context Package in Go – Timeouts, Cancellation, and Best Practices
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)