本帖最后由 psvajaz 于 2023-3-24 16:46 编辑
这个是我自己写的一个MySQL操作类的构造函数,你可以参考一下
[C++] 纯文本查看 复制代码
///
/// \brief The Exception class 异常捕捉类
///
class SQLException{
public:
///
/// \brief ErrorCode 错误代码
///
QString ErrorCode;
///
/// \brief ErrorType 错误类型
///
QString ErrorType;
///
/// \brief ErrorText 错误内容
///
QString ErrorText;
///
/// \brief Message 提示信息
///
QString Message;
///
/// \brief SQLException 异常捕捉类
/// \param errorCode 错误代码
/// \param errorType 错误类型
/// \param errorText 错误内容
/// \param message 提示信息
///
SQLException(QString errorCode, QString errorType, QString errorText, QString message){
this->ErrorCode = ErrorCode.replace("\"", "'");
this->ErrorType = errorType.replace("\"", "'");
this->ErrorText = errorText.replace("\"", "'");
this->Message = message.replace("\"", "'");
}
};
/// \brief MySQLHelper 构造函数
/// \param host 服务器地址
/// \param port 端口
/// \param user 账号
/// \param password 密码
///
MySQLHelper::MySQLHelper(QString host, int port, QString user, QString password)
{
if (QSqlDatabase::contains(host + ":" + QString::number(port))){
this->dbconn = QSqlDatabase::database(host + ":" + QString::number(port));
} else {
this->dbconn = QSqlDatabase::addDatabase("QMYSQL", host + ":" + QString::number(port));
this->dbconn.setHostName(host);
this->dbconn.setPort(port);
this->dbconn.setUserName(user);
this->dbconn.setPassword(password);
}
if (!this->dbconn.isOpen()){
if (!this->dbconn.open()){
try{
this->checkError(this->dbconn.lastError());
} catch (SQLException e) {
throw SQLException(e.ErrorCode, e.ErrorType, e.ErrorType, e.Message);
}
}
}
}
////// \brief checkError 处理SQL异常
/// \param sqlError
///
void MySQLHelper::checkError(QSqlError sqlError)
{
if (sqlError.type() != QSqlError::NoError){
switch (sqlError.type()) {
case QSqlError::ConnectionError:
throw SQLException(sqlError.nativeErrorCode(), QString::number(sqlError.type()), sqlError.text(), "Connection error.");
break;
case QSqlError::StatementError:
throw SQLException(sqlError.nativeErrorCode(), QString::number(sqlError.type()), sqlError.text(), "SQL statement syntax error.");
break;
case QSqlError::TransactionError:
throw SQLException(sqlError.nativeErrorCode(), QString::number(sqlError.type()), sqlError.text(), "Transaction failed error.");
break;
case QSqlError::UnknownError:
throw SQLException(sqlError.nativeErrorCode(), QString::number(sqlError.type()), sqlError.text(), "Unknown error.");
break;
default:
throw SQLException(sqlError.nativeErrorCode(), QString::number(sqlError.type()), sqlError.text(), "Unknown error.");
break;
}
}
}
|