-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlxconcepts.slide
76 lines (43 loc) · 2.05 KB
/
sqlxconcepts.slide
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
sqlx Concepts
Brian Ketelsen
@bketelsen
* sqlx
Why sqlx?
Now that you've seen how to do it the hard way, we're going to learn how to use sqlx, which is a set of extensions on top of db/sql intended to make it easier to use without being magic or surprising.
Features that make it worthwhile:
- Marshal rows into structs (with embedded struct support), maps, and slices
- Named parameter support including prepared statements
- Get and Select to go quickly from query to struct/slice
- Just the first one is enough reason to use sqlx - scanning fields into structs is a pain!
* sqlx Concepts
Connecting
A DB instance is not a connection, but an abstraction representing a Database. This is why creating a DB does not return an error and will not panic. It maintains a connection pool internally, and will attempt to connect when a connection is first needed. You can create an sqlx.DB via Open or by creating a new sqlx DB handle from an existing sql.DB via NewDb
var db *sqlx.DB
// exactly the same as the built-in
db = sqlx.Open("sqlite3", ":memory:")
// from a pre-existing sql.DB; note the required driverName
db = sqlx.NewDb(sql.Open("sqlite3", ":memory:"), "sqlite3")
* Connect
You may want to connect and ensure that your database is available at the same time:
var err error
// open and connect at the same time:
db, err = sqlx.Connect("sqlite3", ":memory:")
// open and connect at the same time, panicing on error
db = sqlx.MustConnect("sqlite3", ":memory:")
* Exercise
Read the rest of the overview of sqlx
.link http://jmoiron.github.io/sqlx/ sqlx overview
* sqlx Exercise
Now let's look at a sqlx version of the first example we did.
cd $GOPATH/src/github.com/bketelsen/sqlx/sqlxquery
view code together
make dockerrun
* sqlx Exercise
Now let's look at a sqlx version of the first example we did.
cd $GOPATH/src/github.com/bketelsen/sqlx/sqlxquery
view code together
make dockerrun
* Exec Assignment
github.com/bketelsen/sqlx/sqlxexec
Finish the insertEmployee() function to insert Elvis into the employee database.