I am using http://github.com/Go-SQL-Driver/MySQL
I want to get a value votes
like "0000" from database and update it into "1000". Before db.Prepare()
it works normally. But after it, the value of votes
is changed. I didn't do anything with it except db.Prepare()
. My code is
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
}
the Votes
type is :
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
}
Finally I copy the value from votes
into v
and it works well. I can not understand why the value of votes
is changed. Is there anything wrong with my code? Any help would be appreciated.