1

我正在尝试将我们的 MySQLdb 连接到我的 MySQL 数据库。当我使用像“fred”这样的有效 mysql 用户名时,一切都按预期工作,但是当我尝试使用像“大な”这样的有效 mysql unicode 用户名、数据库或密码时,一切都会失败。

谁知道如何将 MySQLdb 与可能的 unicode 字符一起使用?

令人惊讶的是,当我使用 mysql.connector 而不是 MySQLdb 时,我可以很好地连接我的数据库、用户和密码中的日文字符(还无法使用日文字符测试主机名)。我很乐意使用 mysql.connector,但我还有另一个问题(请参阅mysql.connector 错误?

def fix(string):
    string = unicode(string)   # convert qstring from pyqt ui to unicode string
    string = string.encode('utf-8') 
    return string

try:
    db = MySQLdb.connect(host=fix(hostname), user=fix(username),  passwd=fix(password), port=int(port), charset="utf8", use_unicode=True)   
except MySQLdb.Error, e:
    errno = e.args[0]
    err = e.args[1]

    reply = QtGui.QMessageBox.critical(self, "MySQL Connect Failed", err.decode("utf8")) 
    return

编辑:我能够解决mysql 连接器错误,所以我将使用 mysql.connector 而不是 MySQLdb,但这个问题仍然有效。

4

1 回答 1

0

该方法中的charset选项在建立连接connect更改字符集。如果您需要 Unicode 来建立连接(例如,因为用户名和/或密码包含 unicode 代码点),那么可以使用该选项。read_default_file

mycnf.cnf 的内容:

[client]
default-character-set=utf8mb4

然后在 Python3 中(最好使用mycnf.cnf文件的绝对路径):

#!/bin/python3

import MySQLdb

user="some name with unicode codepoints"
passwd="unicode password"
db = MySQLdb.connect(
    host="127.0.0.1", 
    user=user, passwd=passwd,
    charset="utf8mb4",
    read_default_file="./mycnf.cnf")

print("db:", db)

db.close()
于 2017-08-25T13:29:41.527 回答