forked from denisenkom/go-mssqldb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
messages_example_test.go
76 lines (68 loc) · 1.52 KB
/
messages_example_test.go
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
75
76
//go:build go1.10
// +build go1.10
package mssql_test
import (
"context"
"database/sql"
"fmt"
"log"
mssql "github.com/denisenkom/go-mssqldb"
"github.com/golang-sql/sqlexp"
)
const (
msgQuery = `select 'name' as Name
PRINT N'This is a message'
select 199
RAISERROR (N'Testing!' , 11, 1)
select 300
`
)
// This example shows the usage of sqlexp/Messages
func ExampleRows_usingmessages() {
connString := makeConnURL().String()
// Create a new connector object by calling NewConnector
connector, err := mssql.NewConnector(connString)
if err != nil {
log.Println(err)
return
}
// Pass connector to sql.OpenDB to get a sql.DB object
db := sql.OpenDB(connector)
defer db.Close()
retmsg := &sqlexp.ReturnMessage{}
ctx := context.Background()
rows, err := db.QueryContext(ctx, msgQuery, retmsg)
if err != nil {
log.Fatalf("QueryContext failed: %v", err)
}
active := true
for active {
msg := retmsg.Message(ctx)
switch m := msg.(type) {
case sqlexp.MsgNotice:
fmt.Println(m.Message)
case sqlexp.MsgNext:
inresult := true
for inresult {
inresult = rows.Next()
if inresult {
cols, err := rows.Columns()
if err != nil {
log.Fatalf("Columns failed: %v", err)
}
fmt.Println(cols)
var d interface{}
if err = rows.Scan(&d); err == nil {
fmt.Println(d)
}
}
}
case sqlexp.MsgNextResultSet:
active = rows.NextResultSet()
case sqlexp.MsgError:
fmt.Println("Error:", m.Error)
case sqlexp.MsgRowsAffected:
fmt.Println("Rows affected:", m.Count)
}
}
}