go-sql-driver / mysql

Go MySQL Driver is a MySQL driver for Go's (golang) database/sql package
https://pkg.go.dev/github.com/go-sql-driver/mysql
Mozilla Public License 2.0
14.44k stars 2.3k forks source link

how can i query with bit field in where clause #1608

Open superceix opened 1 month ago

superceix commented 1 month ago

table info

-- table define
CREATE TABLE `t0` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `c1` int(11) NOT NULL,
  `c2` varchar(64) COLLATE utf8mb4_bin NOT NULL,
  `c3` bit(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin

-- row insert
insert into t0 values (1,1,'aaa',b'1100');

Example code

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    connStr := "xxx:xxx@tcp(xxxxx:xxxx)/?timeout=3600s"
    if conn, err := sql.Open("mysql", connStr); err != nil {
        fmt.Print("ReCreate conn failure!", err.Error())
    } else {
        sql1 := "SELECT c3 FROM `test1`.`t0` WHERE `c2`=?"
        rows1 := conn.QueryRow(sql1, "aaa")
        c3 := []byte{}
        rows1.Scan(&c3)  // row scan success, and get c3 is '[0] = 12 = 0xc' in debug

        sql := "SELECT c2 FROM `test1`.`t0` WHERE `c3`=?"
        rows, err := conn.Query(sql, c3)
        if err != nil {
            fmt.Printf("quert errpor")
        }
        for rows.Next() {
            var c2 string
            if err := rows.Scan(&c2); err != nil {
                fmt.Print("Row.Scan rawRecord Error", err)
            }
            fmt.Printf("c2:%s", c2)
        }
    }
}

no rows result after conn.Query(sql, c3)

methane commented 1 month ago

Try query with mysql cli first.