MySQL: only set the charset if the connection has succeeded

No point otherwise. But do it before trying to select the database, in
case the database name has non-US-ASCII characters.

Task-number: QTBUG-97054
Pick-to: 6.2 6.2.1
Change-Id: Iea05060bc2c046928536fffd16adf036367b07bb
Reviewed-by: Liang Qi <liang.qi@qt.io>
This commit is contained in:
Thiago Macieira 2021-10-14 08:45:55 -07:00
parent 11f5c07c1b
commit 9ecf72704d

View File

@ -1304,6 +1304,15 @@ bool QMYSQLDriver::open(const QString& db,
unixSocket.isNull() ? nullptr : unixSocket.toUtf8().constData(), unixSocket.isNull() ? nullptr : unixSocket.toUtf8().constData(),
optionFlags); optionFlags);
if (mysql != d->mysql) {
setLastError(qMakeError(tr("Unable to connect"),
QSqlError::ConnectionError, d));
mysql_close(d->mysql);
d->mysql = nullptr;
setOpenError(true);
return false;
}
// now ask the server to match the charset we selected // now ask the server to match the charset we selected
if (!cs || mysql_set_character_set(d->mysql, cs->csname) != 0) { if (!cs || mysql_set_character_set(d->mysql, cs->csname) != 0) {
bool ok = false; bool ok = false;
@ -1319,24 +1328,16 @@ bool QMYSQLDriver::open(const QString& db,
mysql_character_set_name(d->mysql)); mysql_character_set_name(d->mysql));
} }
if (mysql == d->mysql) { if (!db.isEmpty() && mysql_select_db(d->mysql, db.toUtf8().constData())) {
if (!db.isEmpty() && mysql_select_db(d->mysql, db.toUtf8().constData())) { setLastError(qMakeError(tr("Unable to open database '%1'").arg(db), QSqlError::ConnectionError, d));
setLastError(qMakeError(tr("Unable to open database '%1'").arg(db), QSqlError::ConnectionError, d));
mysql_close(d->mysql);
setOpenError(true);
return false;
}
if (reconnect)
mysql_options(d->mysql, MYSQL_OPT_RECONNECT, &reconnect);
} else {
setLastError(qMakeError(tr("Unable to connect"),
QSqlError::ConnectionError, d));
mysql_close(d->mysql); mysql_close(d->mysql);
d->mysql = nullptr;
setOpenError(true); setOpenError(true);
return false; return false;
} }
if (reconnect)
mysql_options(d->mysql, MYSQL_OPT_RECONNECT, &reconnect);
d->preparedQuerysEnabled = checkPreparedQueries(d->mysql); d->preparedQuerysEnabled = checkPreparedQueries(d->mysql);
#if QT_CONFIG(thread) #if QT_CONFIG(thread)