golang: sql 操作插入字节数组([]byte)到BLOB字段类型

下列代码中较为特别的转换就是将字节数组写入到数据库中

 fmt.Sprintf("X'%x'", t) 注意插入的时候使用占位符x, 再有一个标志X

func toInsertSQL(dat map[string]interface{}) string {
    if nil == dat { return "" }
	var sql = "INSERT INTO " + tableName
	var keyStr, valueStr = "(", "("

	var index = 0
	var count = len(dat)
	for k, v := range dat {
		keyStr += "\""+ k + "\""
		index += 1
		valueStr += toString(v)
		if index < count { valueStr += ","; keyStr += "," }
	}
	valueStr += ")"
	keyStr += ")"
	sql += " " + keyStr + " VALUES" + valueStr + ";"
	return sql
} 

func toString(v interface{}) string {
	/* 类型是否为指针, 值是否为空, 判断顺序不能颠倒 */
	if reflect.Ptr == reflect.TypeOf(v).Kind() && reflect.ValueOf(v).IsNil() {
		return "NULL"
	}
	switch t := v.(type) {
	case time.Time: return fmt.Sprintf("'%s'", t.Format("2006-01-02 15:04:05.999999999-07:00"))//(sqlite3.SQLiteTimestampFormats[0]))
	case *time.Time: return fmt.Sprintf("'%s'", (*t).Format("2006-01-02 15:04:05.999999999-07:00"))//(sqlite3.SQLiteTimestampFormats[0]))
	case string : return fmt.Sprintf("'%s'", toDoubleQuote(t))
	case *string: return fmt.Sprintf("'%s'", toDoubleQuote(*t))
	case []byte: return fmt.Sprintf("X'%x'", t)
	case *[]byte: return fmt.Sprintf("X'%x'", *t)
	default:
		return fmt.Sprintf("%v", t)
	}
}
上一篇:C语言-sprintf的用法---@颜麓


下一篇:C语言sprintf与sscanf函数