Learn how to interact with a database using Go.
Databases allow you to store and manage information persistently, unlike in-memory variables.
Make sure you have PostgreSQL or MySQL installed and configured.
For PostgreSQL, use:
sudo apt update && sudo apt install postgresql
For MySQL, use:
sudo apt update && sudo apt install mysql-server
We use the `database/sql` package and a driver like `pq` for PostgreSQL or `mysql` for MySQL.
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq" // PostgreSQL driver
)
const dsn = "user=postgres password=secret dbname=mydb sslmode=disable"
func main() {
db, err := sql.Open("postgres", dsn)
if err != nil {
panic(err)
}
defer db.Close()
fmt.Println("Successfully connected to the database!")
}
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
db, _ := sql.Open("postgres", "user=postgres password=secret dbname=mydb sslmode=disable")
defer db.Close()
_, err := db.Exec("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)")
if err != nil {
panic(err)
}
fmt.Println("Table created successfully")
}
database.go
.package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=postgres password=secret dbname=mydb sslmode=disable")
if err != nil {
panic(err)
}
defer db.Close()
db.Exec("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)")
db.Exec("INSERT INTO users (name) VALUES ($1)", "Alice")
rows, _ := db.Query("SELECT id, name FROM users")
defer rows.Close()
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
fmt.Printf("ID: %d, Name: %s\n", id, name)
}
}
📚 Learn more about database usage in Go:
Read the Official Documentation ← Previous Exercise Next Exercise →🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊