Python 中从 MySQL 返回的字符串

问题描述 投票:0回答:3

我尝试使用此 Python 脚本从 MySQL 数据库检索值:

import mysql.connector
from mysql.connector import errorcode

config_file = {}
try:
  cnx = mysql.connector.connect(<removed.)
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with your user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exists")
  else:
    print(err)
else:

  cursor = cnx.cursor()

  cursor.execute("SELECT config_key, config_value FROM T_ConfigTable")

  for (config_key, config_value) in cursor:
    print("{}: {}".format( config_key, config_value))
    config_file[config_key] = config_value

  cursor.close

  cnx.close

  print( config_file)

但结果总是返回:

b'值1':b'值2'

等等

我怎样才能摆脱b?

我使用Python 3.2

感谢您的帮助

python mysql
3个回答
1
投票

您可以使用

config_value.decode('utf-8')


0
投票

有关字符串前面的单/双字母的更多详细信息,请参阅此问题:“b”字符在字符串文字前面做什么?

如果您使用的是 Python 2.x,则

b
将被忽略,并且仅将其视为字符串。如果您使用的是 Python 3.x,则
b
前缀表示它当前采用字节格式。

假设您使用的是 Python 2.x,只需将 config_value 转换为字符串即可:

print str(config_value)


0
投票

我遇到了同样的问题并从这里得到了解决方案: 如何在 MySQL 中将 BLOB 转换为 TEXT?

供您参考 附注我在win10中使用python 3.7并连接远程mysql 8.3

© www.soinside.com 2019 - 2024. All rights reserved.