How to return str from MySQL using mysql.connector?

后端 未结 5 1069
慢半拍i
慢半拍i 2020-12-16 16:06

I\'m trying to use MySQL Connector/Python from mysql.com with Python 3.

I have tables in UTF-8 coding, and when I fetch the rows, all my chars columns returned like

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 17:03

    An easy way to solve this issue is to make sure that you are retrieving 'strings' from your MySQL table. To do so, you just have to add a CAST in your query as follows:

     # -*- coding: utf-8 -*-
    import mysql.connector
    con = mysql.connector.connect( user ="root", db = "vg_site_db", charset = 'utf8' )
    cursor = con.cursor()
    sql = "select CAST(caption as CHAR(50)) from domains"
    cursor.execute( sql )
    row = cursor.fetchone()
    while row is not None:
        print( row )
        row = cursor.fetchone()
    

    This should work for you.

提交回复
热议问题