代码:
package main import ( _ "github.com/go-sql-driver/MysqL" "fmt" "database/sql" ) func main() { d13() fmt.Println("--------------------------") d14() } func d13(){ var err error connect := "f:f@tcp(192.168.1.0:3306)/lr1" db,err := sql.Open("MysqL",connect) if err != nil{ fmt.Println("connect MysqL Failed,address = " + connect,err) } else{ sqlContent := "select real_nm,sex,birth,ext from member where tenant=? and mem_id=?" rows,err := db.Query(sqlContent,"ST","2017") if err != nil{ fmt.Println(err) } else{ for rows.Next() { var nm string var sex string var birth string var ext string err := rows.Scan(&nm,&sex,&birth,&ext) // birth字段在数据库中是空字段 if err != nil{ fmt.Println("d11 error. ",err) } fmt.Println(nm) fmt.Println(sex) fmt.Println(birth) fmt.Println(ext) } } } } func d14(){ var err error connect := "f:f@tcp(192.168.1.0:3306)/lr1" db,"2017") if err != nil{ fmt.Println(err) } else{ for rows.Next() { nm := sql.NullString{String:"",Valid:false} sex := sql.NullString{String:"",Valid:false} birth := sql.NullString{String:"",Valid:false} ext := sql.NullString{String:"",Valid:false} err := rows.Scan(&nm,&ext) // birth字段在数据库中是空字段 if err != nil{ fmt.Println("d12 error. ",err) } fmt.Println(nm.String) fmt.Println(sex.String) fmt.Println(birth.String) fmt.Println(ext.String) } } } }
运行结果截图:
因为数据库的birth字段为空,所以它在给golang的string对象birth赋值时,出错了(golang的 string不能等于nil)所以后续的数据库的ext就没有再赋值给golang的ext对象了, 而是返回error对象
参考路径: