Python MySQL connector returns bytearray instead of regular string value

三世轮回 提交于 2021-01-28 22:08:06

问题


I am loading data from one table into pandas and then inserting that data into new table. However, instead of normal string value I am seeing bytearray.

bytearray(b'TM16B0I8') it should be TM16B0I8

What am I doing wrong here?

My code:

engine_str = 'mysql+mysqlconnector://user:pass@localhost/db'
engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8')
connection = engine.connect()

th_df = pd.read_sql('select ticket_id, history_date', con=connection)

for row in th_df.to_dict(orient="records"):
    var_ticket_id = row['ticket_id']
    var_history_date = row['history_date']

    query = 'INSERT INTO new_table(ticket_id, history_date)....'

回答1:


For some reason the Python MySql connector only returns bytearrys, (more info in (How return str from mysql using mysql.connector?) but you can decode them into unicode strings with

var_ticket_id = row['ticket_id'].decode()
var_history_date = row['history_date'].decode()



回答2:


Make sure you are using the right collation, and encoding. I happen to use UTF8MB4_BIN for one of my website db tables. Changed it to utf8mb4_general_ci, and it did the trick.



来源:https://stackoverflow.com/questions/40921341/python-mysql-connector-returns-bytearray-instead-of-regular-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!