注意一点就行,输出参数和返回值要在结果集处理之后才能获取,这点有点不太科学,代码如下:
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
mssql "github.com/denisenkom/go-mssqldb"
)
func TestDBOperation() {
ctx := context.Background()
query := url.Values{}
query.Add("database", "TestDB") // db name
u := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword("test", "123456"),
Host: fmt.Sprintf("%s:%d", "127.0.0.1", 3433),
RawQuery: query.Encode(),
}
fmt.Println("connection string:", u.String())
db, err := sql.Open("sqlserver", u.String())
if err != nil {
fmt.Println("open err:", err.Error())
return
}
fmt.Println("open success")
var outParameter1 int32
var outParameter2 int32
outParameter1 = 0
outParameter2 = 0
var rs mssql.ReturnStatus
rs = 0
result, err := db.QueryContext(ctx,
`p_test`,
sql.Named("userId", 1000),
sql.Named("outParam1", sql.Out{Dest: &outParameter1}),
sql.Named("outParam2", sql.Out{Dest: &outParameter2}), &rs)
if err != nil {
fmt.Println("exec err:", err.Error())
return
}
var count = 0
var i = 0
var j = 0
for cont := true; cont; cont = result.NextResultSet() {
i++
for result.Next() {
var userInfo UserInfo
err = result.Scan(&userInfo.UserId, &userInfo.HeroId, &userInfo.PropertyId, &userInfo.Level, &userInfo.TrialLevel)
fmt.Println(userInfo)
count++
j++
}
fmt.Printf("i:%d, j:%d\n", i, j)
}
fmt.Printf("out1:%d, out2:%d, rs:%d\n", outParameter1, outParameter2, rs)
defer db.Close()
}
main 函数就不写了