Skip to content

Module 1: SQL Standard Library (The Filing Cabinet)

📚 Module 1: database/sql

Course ID: GO-204
Subject: The Filing Cabinet

Go provides a standard way to talk to any SQL database. Whether you use MySQL, Postgres, or SQLite, the code you write is almost identical.


🏗️ Step 1: The Driver

🧩 The Analogy: The Universal Remote

  • Go has a “Universal Button” for Connecting and Querying.
  • But you need a Driver (A specific code plugin) to tell the remote how to talk to your specific TV (The Database).

🏗️ Step 2: Executing Queries

// 1. Open the drawer (Connection)
db, err := sql.Open("mysql", "user:pass@/dbname")

// 2. Write a single record (Execution)
_, err = db.Exec("INSERT INTO users (name) VALUES (?)", "Alice")

// 3. Find one record (QueryRow)
var name string
err = db.QueryRow("SELECT name FROM users WHERE id = ?", 1).Scan(&name)

🏗️ Step 3: Prepared Statements (The “Safety Guard”)

Notice the ? in the code above? This is a Prepared Statement.

  • The Problem: Hackers can try to type SQL commands into your search box (SQL Injection).
  • The Solution: The ? acts as a placeholder. The database fills in the data safely, so no hacker commands can ever run.

🥅 Module 1 Review

  1. sql.Open: Opening a connection.
  2. db.Exec: Changing data (Insert/Update/Delete).
  3. db.Query: Reading data.
  4. SQL Injection: Always use ? to keep your app safe.

:::tip Slow Learner Note You’ll need to “Scan” the results into Go variables. It feels a bit repetitive, but it ensures your data is exactly what you expect! :::