You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on May 24, 2023. It is now read-only.
Copy file name to clipboardExpand all lines: assigning.md
+21-25Lines changed: 21 additions & 25 deletions
Original file line number
Diff line number
Diff line change
@@ -14,18 +14,16 @@ There are two special cases: nullable columns, and variable numbers of columns,
14
14
15
15
Nullable columns are annoying and lead to a lot of ugly code. If you can, avoid them. If not, then you'll need to use special types from the `database/sql` package to handle them. There are types for nullable booleans, strings, integers, and floats. Here's how you use them:
16
16
17
-
```go
18
-
for rows.Next() {
19
-
vars sql.NullString
20
-
err:= rows.Scan(&s)
21
-
// check err
22
-
if s.Valid {
23
-
// use s.String
24
-
} else {
25
-
// NULL value
17
+
for rows.Next() {
18
+
var s sql.NullString
19
+
err := rows.Scan(&s)
20
+
// check err
21
+
if s.Valid {
22
+
// use s.String
23
+
} else {
24
+
// NULL value
25
+
}
26
26
}
27
-
}
28
-
```
29
27
30
28
Limitations of the nullable types, and reasons to avoid nullable columns in case you need more convincing:
31
29
@@ -35,20 +33,18 @@ Limitations of the nullable types, and reasons to avoid nullable columns in case
35
33
36
34
The other special case is assigning a variable number of columns into variables. The `rows.Scan()` function accepts a variable number of `interface{}`, and you have to pass the correct number of arguments. If you don't know the columns or their types, you should use `sql.RawBytes`:
37
35
38
-
```go
39
-
cols, err:= rows.Columns() // Get the column names; remember to check err
ints := make([]interface{}, len(cols)) // Make a slice of []interface{}
39
+
for i := range ints {
40
+
ints[i] = &vals[i] // Copy references into the slice
41
+
}
42
+
for rows.Next() {
43
+
err := rows.Scan(vals...)
44
+
// Now you can check each element of vals for nil-ness,
45
+
// and you can use type introspection and type assertions
46
+
// to fetch the column into a typed variable.
47
+
}
52
48
53
49
If you know the possible sets of columns and their types, it can be a little less annoying, though still not great. In that case, you simply need to examine `rows.Columns()`, which returns an array of column names.
0 commit comments