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

标签 postgresql go pq

我正在尝试将 txt 写入 postgres 批量导入器。代码当前崩溃,因为应插入到 postgres 的字符串不是有效的 UTF8:pq:编码 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:hushpuppiieslove

splitLine[0] + splitLine[1]:username@hotmail.whatever hushpuppiieslove

最佳答案

0x00 是空字符,postgres 不允许在字符串中使用。来自 the docs :

The NULL (0) character is not allowed because text data types cannot store such bytes.

您需要去除空字符。

关于postgresql - 尽管字符串是有效的 UTF8,但字节序列无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56381764/

相关文章:

sql - 将自动增量值添加到与另一列中的重复值相关的列

go - golangs sqlx.DB.Select() 语句中的 Bindvars 需要 0 个参数

go - 调用 db.Ping() 时的无限循环

php - Adodb 使用 php 和 PostgreSQL

postgresql - 取消组合 postgres 中的列

reactjs - 您如何使用 fetch 在本地从客户端向服务器发出请求而不会得到不透明的响应?

performance - 如何有效地在文件中插入 byte slice ?

sql - 拒绝两个字段中的空值

go - 安装 revel : undefined: config. DEFAULT_SECTION 时出错