liveBook · Manning

SQL

As explained in Go by Example

An SQL query is a statement expressed in SQL that requests or modifies data in a relational database.

SQL is a language for requesting or modifying data in a relational database. In Go, database/sql supplies a uniform API: a registered database driver connects the API to a specific database, while *sql.DB manages execution through a connection pool. section 10.1

Use SQL from Go by combining these pieces:

  • Register a community-provided driver, then call sql.Open with its name and a database-specific connection string. section 10.1
  • Execute statements through *sql.DB; the pool selects, opens, closes, and retries connections as needed. section 10.1
  • Pass context.Context downstream so cancellation can stop an ongoing database operation. section 10.2.1
  • Use placeholders instead of handcrafted SQL parameters to reduce the likelihood of SQL injection, while accounting for database-specific placeholder syntax. section 10.2.1

Insert a shortened link

A service can persist a shortened link with a context-aware SQL statement: _, err = s.db.ExecContext( ctx, `INSERT INTO links (short_key, uri) VALUES ($1, $2)`, lnk.Key, lnk.URL, ) The dollar-sign placeholders receive the key and URL as separate arguments. This query is PostgreSQL-compatible, though placeholder syntax may differ across databases. section 10.2.1

Figure 10.1 The sql package abstracts underlying databases with drivers. The sql package’s registry stores registered drivers, and *DB manages a connection pool.
A computer screen shot of a computer

AI-generated content may be incorrect.

Shows how database/sql, its driver registry, and *sql.DB's connection pool separate application code from the underlying database technology. section 10.1

How Go by Example covers it

How deep it goes
Explains driver registration, connection pooling, context cancellation, insertion, and placeholders, but stops short of broader query operations.
Examples
Demonstrates SQLite and PostgreSQL opening, then inserts shortened-link keys and URLs with ExecContext.
What it assumes
Assumes a SQL database and driver while teaching database/sql usage, driver registration, pooling, and context-aware execution.
What you can do after
Operate/configure Go database access, execute parameterized SQL, and cancel operations through context.Context.
How it connects
Connects SQL with relational databases, database drivers, connection pools, context cancellation, SQL injection, and SQL dialects.

Also explained in

Compare how 25 books explain SQL →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.