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.
Shows how database/sql, its driver registry, and *sql.DB's connection pool separate application code from the underlying database technology. section 10.1
























