为了账号安全,请及时绑定邮箱和手机立即绑定

尽管字符串是有效的 UTF8,但字节序列无效

尽管字符串是有效的 UTF8,但字节序列无效

Go
杨__羊羊 2023-06-19 17:23:07
我正在尝试将 txt 写入 postgres 批量导入器。该代码当前崩溃,因为应该插入到 postgres 的字符串不是有效的 UTF8:pq: invalid byte sequence for encoding UTF8: 0x00在我的代码中,我正在检查字符串是否为有效的 UTF8。我错过了什么?代码:for {        line, more := <-lineChannel        splitLine := strings.SplitN(line, ":", 2)        if len(splitLine) == 2 {            if utf8.Valid([]byte(splitLine[0])) && utf8.Valid([]byte(splitLine[1])) {                lineCount++                _, err = stmt.Exec(splitLine[0], splitLine[1])                if lineCount%int64(copySize) == 0 {                    _, err = stmt.Exec()                    if err != nil {                        log.Fatal("Failed at stmt.Exec", err)                    }                    err = stmt.Close()                    if err != nil {                        log.Fatal("Failed at stmt.Close", err)                    }                    err = txn.Commit()                    if err != nil {                        log.Fatal("failed at txn.Commit", err)                    }                    txn, err = db.Begin()                    if err != nil {                        log.Fatal("failed at db.Begin", err)                    }                    stmt, err = txn.Prepare(pq.CopyIn("pwned", "username", "password"))                    if err != nil {                        log.Fatal("failed at txn.Prepare", err)                    }                    if lineCount%(int64(copySize)*10) == 0 {                        log.Printf("Inserted %v lines", lineCount)                    }                }                if err != nil {                    log.Println("error:", splitLine[0], splitLine[1])                    log.Fatal(err)                }            }编辑:出错的行:字节[]:[116 109 97 105 108 46 99 111 109 58 104 117 115 104 112 117 112 112 105 101 115 108 111 118 101]线:username@hotmail.whatever:hushpuppieslove分割线[0] + 分割线[1]:username@hotmail.whatever hushpuppieslove
查看完整描述

1 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

0x00 是空字符,postgres 不允许在字符串中使用。从文档:

NULL (0) 字符是不允许的,因为文本数据类型不能存储此类字节。

您需要删除空字符。


查看完整回答
反对 回复 2023-06-19
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信