SlideShare a Scribd company logo
DATABASE/SQL
• github.com/VividCortex
• @xaprb
• baron@vividcortex.com
• linkedin.com/in/xaprb
Optimization, Backups,
Replication, and more
Baron Schwartz,
Peter Zaitsev &
Vadim Tkachenko
High
Performance
MySQL
3rd
Edition
CoversVersion
5.5
ME
• Docs: golang.org/pkg/database/sql/
• Tutorial: go-database-sql.org/
• MySQL Driver: github.com/go-sql-driver/mysql/
RESOURCES
THINGS
DB
• Not a connection.
• Open() Close()
• Query() QueryRow() Exec()
ROWS
• Next()
• Scan()
PATTERNS
package main
import (
! _ "github.com/go-sql-driver/mysql"
! "database/sql"
! "log"
)
func main() {
! db, err := sql.Open("mysql",
! ! "user:password@tcp(127.0.0.1:3306)/test")
! if err != nil {
! ! log.Println(err)
! }
! // What do we have here?
! defer db.Close()
}
var str string
err = db.QueryRow(
"select hello from world where id = 1").
Scan(&str)
if err != nil && err != sql.ErrNoRows {
log.Println(err)
}
log.Println(str)
q := "select id, hello from world where id = ?"
rows, err := db.Query(q, 1)
if err != nil {
! log.Fatal(err)
}
defer rows.Close()
var id int
var str string
for rows.Next() {
! err = rows.Scan(&id, &str)
! if err != nil {
! ! log.Fatal(err)
! }
! // Use the variables scanned from the row
}
for rows.Next() {
! // scan
}
if err = rows.Err(); err != nil {
rows.Close()
log.Fatal(err)
}
stmt, err := db.Prepare(
! "select id, hello from world where id = ?")
if err != nil {
! log.Fatal(err)
}
defer stmt.Close()
rows, err := stmt.Query(1)
if err != nil {
! log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
! // ...
}
stmt, err := db.Prepare(
! "insert into world(hello) values(?)")
if err != nil {
! log.Fatal(err)
}
defer stmt.Close()
res, err := stmt.Exec("hello, Dolly")
if err != nil {
! log.Fatal(err)
}
THINGSTO KNOW
THINGSTO KNOW
• There is a connection pool.
• You can’t use uint64 with high bit set in parameters.
DON’T BE LAZY
// Don’t do this!
for i := 0; i < 50; i++ {
! _, err := db.Query("DELETE FROM hello.world")
}
// Use this instead!
for i := 0; i < 50; i++ {
! _, err := db.Exec("DELETE FROM hello.world")
}
MORE HELPFUL ADVICE
• Don’t defer() in long-running functions.
• Don’t use cxn state. UseTx to bind to a connection.
• Don’t use BEGIN and COMMIT via SQL.
SURPRISES
RETRY. RETRY. RETRY. RETRY. RETRY.
RETRY. RETRY. RETRY. RETRY. RETRY.
// Exec executes a query without returning any
rows.
// The args are for any placeholder parameters in
the query.
func (db *DB) Exec(query string,
args ...interface{}) (Result, error) {
! var res Result
! var err error
! for i := 0; i < 10; i++ {
! ! res, err = db.exec(query, args)
! ! if err != driver.ErrBadConn {
! ! ! break
! ! }
! }
! return res, err
}
PREPARED STATEMENTS
NULL
This page intentionally left blank.
var s sql.NullString
err := db.QueryRow(
"SELECT name FROM foo WHERE id=?",
id).Scan(&s)
if s.Valid {
// use s.String
} else {
// NULL value
}
CUSTOMTYPES
CUSTOMTYPES
• You can implement theValuer and Scanner interfaces.
• Why?Transparently transform data in <=> out of the DB.
• Compress and uncompress.
• Marshall/unmarshall JSON or another type.
• Encrypt and decrypt.
• See e.g. http://jmoiron.net/blog/built-in-interfaces/
RESOURCES
• http://golang.org/pkg/database/sql/
• http://go-database-sql.org/
• https://github.com/go-sql-driver/mysql
• http://jmoiron.net/blog/
• @VividCortex * not biased, not biased, not biased
IMAGE CREDITS
• http://www.flickr.com/photos/simens/6306917636/
• http://www.flickr.com/photos/dexxus/5794905716/
• http://www.flickr.com/photos/sebastian_bergmann/202396633/
• http://www.flickr.com/photos/doug88888/4794114114/
• http://www.flickr.com/photos/oatsy40/6443878013/
• http://www.sxc.hu/photo/1160562/
• Google Maps (screenshot)
• http://www.flickr.com/photos/estherase/13553883/
• http://www.flickr.com/photos/paperpariah/4150220583/
• http://www.flickr.com/photos/zooboing/4743616313/
• http://www.flickr.com/photos/dseneste/5912382808/
• http://www.flickr.com/photos/clickykbd/66165381/sizes/l/
• http://www.flickr.com/photos/mamnaimie/5576980406/
• https://www.flickr.com/photos/zachstern/87431231

More Related Content

PDF
MySQL in Go - Golang NE July 2015
PPT
Building a Testable Data Access Layer
PDF
Debugging and Testing ES Systems
PDF
Building Distributed System with Celery on Docker Swarm
PDF
An Introduction to Celery
PDF
Celery with python
KEY
Django Celery
PDF
ElasticSearch
MySQL in Go - Golang NE July 2015
Building a Testable Data Access Layer
Debugging and Testing ES Systems
Building Distributed System with Celery on Docker Swarm
An Introduction to Celery
Celery with python
Django Celery
ElasticSearch

What's hot (20)

PDF
Celery - A Distributed Task Queue
PDF
Why Task Queues - ComoRichWeb
ODP
Europython 2011 - Playing tasks with Django & Celery
PDF
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
PDF
Web Crawling with NodeJS
PDF
Scaling up task processing with Celery
PPTX
MongoDB: tips, trick and hacks
PDF
Got Logs? Get Answers with Elasticsearch ELK - PuppetConf 2014
PDF
Django Celery - A distributed task queue
PDF
Performance and stability testing \w Gatling
PPTX
Introduction to PostgreSQL
PDF
Selenium sandwich-3: Being where you aren't.
ODP
My app is secure... I think
PDF
Real-time search in Drupal. Meet Elasticsearch
PDF
Ember background basics
ODP
Beyond PHP - it's not (just) about the code
PDF
Activator and Reactive at Play NYC meetup
ODP
When dynamic becomes static: the next step in web caching techniques
PDF
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
PPTX
Asynchronous Task Queues with Celery
Celery - A Distributed Task Queue
Why Task Queues - ComoRichWeb
Europython 2011 - Playing tasks with Django & Celery
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Web Crawling with NodeJS
Scaling up task processing with Celery
MongoDB: tips, trick and hacks
Got Logs? Get Answers with Elasticsearch ELK - PuppetConf 2014
Django Celery - A distributed task queue
Performance and stability testing \w Gatling
Introduction to PostgreSQL
Selenium sandwich-3: Being where you aren't.
My app is secure... I think
Real-time search in Drupal. Meet Elasticsearch
Ember background basics
Beyond PHP - it's not (just) about the code
Activator and Reactive at Play NYC meetup
When dynamic becomes static: the next step in web caching techniques
Stubる - Mockingjayを使ったHTTPクライアントのテスト -
Asynchronous Task Queues with Celery
Ad

Viewers also liked (11)

PDF
Fraser Graham Killer Robots
PDF
High Performance Systems in Go - GopherCon 2014
PDF
A Channel Compendium
PPTX
Building A Relevancy Engine Using MongoDB and Go
PDF
Best practices-for-production-environments
PDF
Garbage collector и управление памятью в Go
PPTX
C-spirit reborn: why Go was bound to be created
PDF
Anthony Starks - deck
PPTX
OOP в Go
PPTX
Talknoteとgolangと私
PDF
GoによるWebアプリ開発のキホン
Fraser Graham Killer Robots
High Performance Systems in Go - GopherCon 2014
A Channel Compendium
Building A Relevancy Engine Using MongoDB and Go
Best practices-for-production-environments
Garbage collector и управление памятью в Go
C-spirit reborn: why Go was bound to be created
Anthony Starks - deck
OOP в Go
Talknoteとgolangと私
GoによるWebアプリ開発のキホン
Ad

Similar to Go database/sql (20)

PDF
Sql and Go
PDF
The powerful toolset of the go-mysql library
PPTX
Modern sql
PPTX
Database connectivity in python
PDF
UAE MySQL Users Group Meet-up : MySQL Shell Document Store & more...
PPTX
harry presentation
PDF
The RDBMS You Should Be Using
PPTX
Chjkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjj01_The Basics.pptx
ODP
Meet the-other-elephant
PPT
3 database-jdbc(1)
PDF
Sangam 19 - Successful Applications on Autonomous
PDF
QB Into the Box 2018
PDF
What SQL should actually be...
PDF
Python and MySQL 8.0 Document Store
PDF
PostgreSQLNotesForProfessionals.pdf
PPTX
PythonDatabaseAPI -Presentation for Database
PDF
Postgresql Up And Running Regina Obe Leo Hsu
PPTX
Database connectivity in python
Sql and Go
The powerful toolset of the go-mysql library
Modern sql
Database connectivity in python
UAE MySQL Users Group Meet-up : MySQL Shell Document Store & more...
harry presentation
The RDBMS You Should Be Using
Chjkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjj01_The Basics.pptx
Meet the-other-elephant
3 database-jdbc(1)
Sangam 19 - Successful Applications on Autonomous
QB Into the Box 2018
What SQL should actually be...
Python and MySQL 8.0 Document Store
PostgreSQLNotesForProfessionals.pdf
PythonDatabaseAPI -Presentation for Database
Postgresql Up And Running Regina Obe Leo Hsu
Database connectivity in python

Recently uploaded (20)

PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Machine Learning_overview_presentation.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
sap open course for s4hana steps from ECC to s4
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Encapsulation_ Review paper, used for researhc scholars
Machine Learning_overview_presentation.pptx
Empathic Computing: Creating Shared Understanding
sap open course for s4hana steps from ECC to s4
“AI and Expert System Decision Support & Business Intelligence Systems”
20250228 LYD VKU AI Blended-Learning.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectroscopy.pptx food analysis technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Assigned Numbers - 2025 - Bluetooth® Document
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Programs and apps: productivity, graphics, security and other tools
The Rise and Fall of 3GPP – Time for a Sabbatical?
Mobile App Security Testing_ A Comprehensive Guide.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Unlocking AI with Model Context Protocol (MCP)
gpt5_lecture_notes_comprehensive_20250812015547.pdf

Go database/sql

  • 2. • github.com/VividCortex • @xaprb • [email protected] • linkedin.com/in/xaprb Optimization, Backups, Replication, and more Baron Schwartz, Peter Zaitsev & Vadim Tkachenko High Performance MySQL 3rd Edition CoversVersion 5.5 ME
  • 3. • Docs: golang.org/pkg/database/sql/ • Tutorial: go-database-sql.org/ • MySQL Driver: github.com/go-sql-driver/mysql/ RESOURCES
  • 5. DB • Not a connection. • Open() Close() • Query() QueryRow() Exec()
  • 8. package main import ( ! _ "github.com/go-sql-driver/mysql" ! "database/sql" ! "log" ) func main() { ! db, err := sql.Open("mysql", ! ! "user:password@tcp(127.0.0.1:3306)/test") ! if err != nil { ! ! log.Println(err) ! } ! // What do we have here? ! defer db.Close() }
  • 9. var str string err = db.QueryRow( "select hello from world where id = 1"). Scan(&str) if err != nil && err != sql.ErrNoRows { log.Println(err) } log.Println(str)
  • 10. q := "select id, hello from world where id = ?" rows, err := db.Query(q, 1) if err != nil { ! log.Fatal(err) } defer rows.Close() var id int var str string for rows.Next() { ! err = rows.Scan(&id, &str) ! if err != nil { ! ! log.Fatal(err) ! } ! // Use the variables scanned from the row }
  • 11. for rows.Next() { ! // scan } if err = rows.Err(); err != nil { rows.Close() log.Fatal(err) }
  • 12. stmt, err := db.Prepare( ! "select id, hello from world where id = ?") if err != nil { ! log.Fatal(err) } defer stmt.Close() rows, err := stmt.Query(1) if err != nil { ! log.Fatal(err) } defer rows.Close() for rows.Next() { ! // ... }
  • 13. stmt, err := db.Prepare( ! "insert into world(hello) values(?)") if err != nil { ! log.Fatal(err) } defer stmt.Close() res, err := stmt.Exec("hello, Dolly") if err != nil { ! log.Fatal(err) }
  • 15. THINGSTO KNOW • There is a connection pool. • You can’t use uint64 with high bit set in parameters.
  • 17. // Don’t do this! for i := 0; i < 50; i++ { ! _, err := db.Query("DELETE FROM hello.world") } // Use this instead! for i := 0; i < 50; i++ { ! _, err := db.Exec("DELETE FROM hello.world") }
  • 18. MORE HELPFUL ADVICE • Don’t defer() in long-running functions. • Don’t use cxn state. UseTx to bind to a connection. • Don’t use BEGIN and COMMIT via SQL.
  • 20. RETRY. RETRY. RETRY. RETRY. RETRY. RETRY. RETRY. RETRY. RETRY. RETRY.
  • 21. // Exec executes a query without returning any rows. // The args are for any placeholder parameters in the query. func (db *DB) Exec(query string, args ...interface{}) (Result, error) { ! var res Result ! var err error ! for i := 0; i < 10; i++ { ! ! res, err = db.exec(query, args) ! ! if err != driver.ErrBadConn { ! ! ! break ! ! } ! } ! return res, err }
  • 24. var s sql.NullString err := db.QueryRow( "SELECT name FROM foo WHERE id=?", id).Scan(&s) if s.Valid { // use s.String } else { // NULL value }
  • 26. CUSTOMTYPES • You can implement theValuer and Scanner interfaces. • Why?Transparently transform data in <=> out of the DB. • Compress and uncompress. • Marshall/unmarshall JSON or another type. • Encrypt and decrypt. • See e.g. http://jmoiron.net/blog/built-in-interfaces/
  • 27. RESOURCES • http://golang.org/pkg/database/sql/ • http://go-database-sql.org/ • https://github.com/go-sql-driver/mysql • http://jmoiron.net/blog/ • @VividCortex * not biased, not biased, not biased
  • 28. IMAGE CREDITS • http://www.flickr.com/photos/simens/6306917636/ • http://www.flickr.com/photos/dexxus/5794905716/ • http://www.flickr.com/photos/sebastian_bergmann/202396633/ • http://www.flickr.com/photos/doug88888/4794114114/ • http://www.flickr.com/photos/oatsy40/6443878013/ • http://www.sxc.hu/photo/1160562/ • Google Maps (screenshot) • http://www.flickr.com/photos/estherase/13553883/ • http://www.flickr.com/photos/paperpariah/4150220583/ • http://www.flickr.com/photos/zooboing/4743616313/ • http://www.flickr.com/photos/dseneste/5912382808/ • http://www.flickr.com/photos/clickykbd/66165381/sizes/l/ • http://www.flickr.com/photos/mamnaimie/5576980406/ • https://www.flickr.com/photos/zachstern/87431231