doushenyu2537 2017-03-23 22:30
浏览 31

GoLang MSSQL泄漏连接

I have strange issue with golang sql and probably denisenkom/go-mssqldb.

My code part:

func Auth(username string, password string, remote_ip string, user_agent string) (string, User, error) {
var token string
var user = User{}

query := `exec dbo.sp_get_user ?,?`

rows, err := DB.Query(query, username, password)
if err != nil {
    return token, user, err
}
defer rows.Close()

rows.Next()
if err = rows.Scan(&user.Id, &user.Username, &user.Description); err != nil {
    log.Printf("SQL SCAN: Failed scan User in Auth. %v 
", err)
    return token, user, err
}

hashFunc := md5.New()
hashFunc.Write([]byte(username + time.Now().String()))

token = hex.EncodeToString(hashFunc.Sum(nil))

query = `exec dbo.sp_set_session ?,?,?,?`

_, err = DB.Exec(query, user.Id, token, remote_ip, user_agent)
if err != nil {
    return token, user, err
}

return token, user, nil
}

Problem: defer rows.Close() - not working properly

After this with DB.Connection.Stats().OpenConnections I always have 2 connection opened (also after repeat User login is still 2 connection for whole app lifecycle)

But if I rewrite func as:

...
    query := `exec dbo.sp_get_user ?,?`

    rows, err := DB.Query(query, username, password)
    if err != nil {
        return token, user, err
    }
    defer rows.Close()

    rows.Next()
    if err = rows.Scan(&user.Id, &user.Username, &user.Description); err != nil {
        log.Printf("SQL SCAN: Failed scan User in Auth. %v 
", err)
        return token, user, err
    }

    rows.Close()
...

Then rows underline stmt is closed and next DB.Connection.Stats().OpenConnections always will be 1 connection open.

DB in my app is simply return underlying connection from sql.Open

Problem is only in this part where two query executions with Query and Exec in one functions.

Maybe Query and Exec defines different connections, but i don't find this in driver source or database/sql source.

Thank you! (sorry for english if it's so bad)

PS:

exec dbo.sp_get_user ?,? - is simple select from user table, not more.

exec dbo.sp_set_session ?,?,?,? - is simple insert to user table, not more

In MSSQL - DBCC INPUTBUFFER shows me query = 'cast(@@identity as bigint)' which executes in denisenkom/go-mssqldb mssql.go on line 593

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 公交车和无人机协同运输
    • ¥15 stm32代码移植没反应
    • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
    • ¥100 连续两帧图像高速减法
    • ¥15 组策略中的计算机配置策略无法下发
    • ¥15 如何绘制动力学系统的相图
    • ¥15 对接wps接口实现获取元数据
    • ¥20 给自己本科IT专业毕业的妹m找个实习工作
    • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
    • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)