我正在使用http://github.com/Go-SQL-Driver/MySQL
我想votes
从数据库中获取类似“0000”的值并将其更新为“1000”。在db.Prepare()
它正常工作之前。但是在它之后, 的值发生了votes
变化。我没有对它做任何事情,除了db.Prepare()
. 我的代码是
func Vote(_type, did int, username string) (isSucceed bool) {
db := lib.OpenDb()
defer db.Close()
stmt, err := db.Prepare(
`SELECT votes
FROM users
WHERE username = ?`)
lib.CheckErr(err)
res := stmt.QueryRow(username)
stmt.Close()
var votes Votes
res.Scan(&votes)
fmt.Println(votes)//output: [48 48 48 48]
fmt.Println(string(votes))//output: 0000
isSucceed = votes.add(VoteType(_type), 1)
fmt.Println(votes)//output: [49 48 48 48]
fmt.Println(string(votes))//output: 1000
//v := []byte{[]byte(votes)[0], []byte(votes)[1], []byte(votes)[2], []byte(votes)[3]}
if isSucceed {
//Update user votes
stmt, err := db.Prepare(
`UPDATE users
SET votes = ?
WHERE username = ?`)
lib.CheckErr(err)
fmt.Println(votes)//output: [4 254 0 0]
fmt.Println(string(votes))//output: [EOT]□[NUL][NUL]
//_, _ = stmt.Exec(v, username)
_, _ = stmt.Exec(votes, username)
stmt.Close()
//Insert the vote data
stmt, err = db.Prepare(
`INSERT votes
SET did = ?, username = ?, date = ?`)
lib.CheckErr(err)
today := time.Now()
_, _ = stmt.Exec(did, username, today)
stmt.Close()
}
return
}
Votes
类型是:
type Votes []byte
type VoteType int
func (this *Votes) add(_type VoteType, num int) (isSucceed bool) {
if []byte(*this)[_type] > VOTE_MAX-1 { //beyond
isSucceed = false
} else {
[]byte(*this)[_type]++
isSucceed = true
}
return
}
最后,我将值从votes
into复制v
,它运行良好。我不明白为什么值votes
会改变。我的代码有什么问题吗?任何帮助,将不胜感激。