Python MySQLdb上传UnicodeEncodeE

2024-10-01 11:29:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我可以上传CSV文件到MySQL,但后来发生了一些事情,我得到了一个编码错误。有人能检查一下我的代码并告诉我出了什么问题吗?我是新手。在

下面的代码片段是我如何编写要上载的CSV文件,数据是使用MDN工具(MDB export)从MDB文件中提取的:

    tableIndex  = 1
    for tName in tableNames:
        fileName = os.path.join(csvPath, os.path.basename(mdb).split('.')[0] + '_' + tName + '.csv')

        try:
            p = subprocess.Popen(["mdb-export", "-H", mdb, tName], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            tableContent, error = p.communicate()

            if(p.returncode != 0):
                _logger.error('[%3d] Export Subprocess %d %s' % (tID, p.returncode, tableContent))
                SendMdbError(tID, mdb, _logger, 'ALERT: Export Subprocess')
                return(['', False])
            if(error):
                _logger.error('[%3d] Export Communicate %d %s' % (tID, p.returncode, error.strip()))
                SendMdbError(tID, mdb, _logger, 'ALERT: Export Communicate')
                return(['', False])

        except Exception as ex:
            _logger.exception('[%3d] Export Error' % tID)
            SendMdbError(tID, mdb, _logger, 'ALERT: Export Exception')
            return(['', False])
        except:
            _logger.exception('[%3d] Export Unexpected' % tID)
            SendMdbError(tID, mdb, _logger, 'ALERT: Export Unexpected')
            return(['', False])

        # If no data, no need for corresponding SQL
        if(len(tableContent) == 0):
            emptyTables.append(tName)

        # If data exists, dump data
        else:
            # Add the 'DriveTest' to the data to upload
            tableContent = tableContent.split('\n')

            tableContent = [dt + ',' + line for line in tableContent if(line)]
            tableContent = '\n'.join(tableContent)

            try:
                with open(fileName, 'wb') as f:
                    f.write(tableContent)

                    if(_VERBOSITY):
                        _logger.debug('[%3d] %3d - Write CSV SIZE[%8d] FILE: %s' %(tID, tableIndex, len(tableContent.split('\n')), fileName))
                        tableIndex += 1

            except IOError as err:
                _logger.exception('[%3d] Write IOError: %s' % (tID, str(err)))
                SendMdbError(tID, mdb, _logger, 'ALERT: Write IOError')
                return(['', False])
            except Exception as ex:
                _logger.exception('[%3d] Write Exception' % tID)
                SendMdbError(tID, mdb, _logger, 'ALERT: Write Exception')
                return(['', False])
            except:
                _logger.exception('[%3d] Write Unexpected: %s' % tID)
                SendMdbError(tID, mdb, _logger, 'ALERT: Write Unexpected')
                return(['', False])

以下是我上载CSV文件的位置,这里是我得到错误的位置:

^{pr2}$

我得到的错误是:

2015-06-13 19:42:21,743 __main__ -    ERROR - [  1]   1 Exception: 'ascii' codec can't encode character u'\xb4' in position 40: ordinal not in range(128) <type 'exceptions.UnicodeEncodeError'>
2015-06-13 19:42:30,962 __main__ -    ERROR - [  1]   1 Exception: 'ascii' codec can't encode character u'\xb4' in position 27: ordinal not in range(128) <type 'exceptions.UnicodeEncodeError'>

我注意到给定的数据被上传了,但是不确定是否所有的行都被上传了。在

谢谢!在


Tags: infalsereturnifexceptionexporterroralert
3条回答

错误消息暗示MySQL中的列定义是CHARACTER SET ascii;正确吗?在

B4听起来像是´的拉丁1(而不是utf8)编码,它可能来自上下文中的Microsoft Word文档,例如it´s。在

因此,即使将列改为CHARACTER SET utf8也不能解决问题。在

BINARY和{}本质上是允许任何字节的相同类型的字段。VARCHARTEXTINSERT期间验证字节,以确保它们与^{匹配。在

在将csv放入DB s.decode('UTF-8')之前和从DB s.encode('UTF-8')中取出csv之前尝试一下

我是为SQLite做的,效果不错。在

让它发挥作用不应该太困难,但你必须明白你在做什么。不要尝试所有可能的组合s.encode("UTF-8").decode("UTF-8")之类的东西。在

首先,了解string和{}之间的区别。见https://docs.python.org/3/howto/unicode.html。可以将字符串编码为字节:bytes = text.encode("UTF-8"),也可以将字节解码为字符串:text = bytes.decode("UTF-8")

第二,由于CSV文件是文本文件,您应该以文本模式打开CSV文件。open(fileName, 'w', encoding="utf-8")。在编写文件时,不需要对代码中的文本进行编码或解码。在

第三,将Unicode文本写入文本字段是完全可以的。不需要二进制或blob。但是要确保您的数据库有一个可以处理它的排序规则设置,通常是utf-8排序规则之一。然后要在数据库中放入Unicode,请使用python字符串,不要将它们解码为字节。在

相关问题 更多 >