golang: sql 操作插入位元組陣列([]byte)到BLOB欄位型別
阿新 • • 發佈:2020-12-04
下列程式碼中較為特別的轉換就是將位元組陣列寫入到資料庫中
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) } }