Bug #82824 "TypeError: can't concat bytes to str" occurred when bytearray is used
Submitted: 31 Aug 2016 13:44 Modified: 17 Nov 2016 13:03
Reporter: ziyang wu Email Updates:
Status: Verified Impact on me:
None 
Category:Connector / Python Severity:S3 (Non-critical)
Version:2.1.3 OS:Any
Assigned to: CPU Architecture:Any

[31 Aug 2016 13:44] ziyang wu
Description:
Table A uses CHARACTER SET utf8 COLLATE utf8_bin and Table A  has column b of varchar type. When use sql "select b from A"  the type of b in python3.4 is bytearray.  When execute "select c from A where b = ?" and pass a bytearray as the param, the following error shows:

Traceback (most recent call last):
  File "D:\Python34\lib\site-packages\mysql\connector\cursor.py", line 361, in _process_params_dict
    conv = quote(conv)
  File "D:\Python34\lib\site-packages\mysql\connector\conversion.py", line 173, in quote
    return bytearray(b"'" + buf + b"'")
TypeError: can't concat bytes to str

The method _process_params_dict in mysql\connector\cursor.py:

    def _process_params_dict(self, params):
        """Process query parameters given as dictionary"""
        try:
            to_mysql = self._connection.converter.to_mysql
            escape = self._connection.converter.escape
            quote = self._connection.converter.quote
            res = {}
            for key, value in list(params.items()):
                conv = value
                conv = to_mysql(conv)
                conv = escape(conv)
                conv = quote(conv)
                if PY2:
                    res["%({0})s".format(key)] = conv
                else:
                    res["%({0})s".format(key).encode()] = conv
        except Exception as err:
            raise errors.ProgrammingError(
                "Failed processing pyformat-parameters; %s" % err)
        else:
            return res

"to_mysql" method in mysql\connector\conversion.py will call _bytearray_to_mysql, which is "return str(value)", so the variable conv  is convert to str type. And in quote method in conversion.py, when it call "bytearray(b"'" + buf + b"'")",   "TypeError: can't concat bytes to str" will be throw.

How to repeat:
Use python3.4 and mysql-connector of 2.1.3, create a table A of CHARACTER SET utf8 COLLATE utf8_bin , and A has column b of varchar type. where pass a var of type bytearray as param to sql like "select c from A where b =?", the same error will be shown.

Suggested fix:
The method _bytearray_to_mysql should not convert bytearray to str.
[17 Nov 2016 13:03] Chiranjeevi Battula
Hello ziyang wu,

Thank you for the bug report.
Verified based on internal discussion with dev's will take it up as a feature request.

Thanks,
Chiranjeevi.