我有一些Qt代码效果很好。但我不满意它的样子。这段代码创建了带有几个表和一些数据的Sqlite数据库,如果出现任何错误报告和错误并进行清理。
我通过这种方式检查错误:
if(!query.exec(queryStr))
{
QMessageBox::critical(this, tr("Error!"), query.LastError().text());
// some cleanup here
this->close();
}
有几个与此代码相关的问题。首先,有时数据库驱动程序(如上所述,Sqlite)会显示自己的错误消息框(如果发生错误)。这些消息框不居中,如果显示它们(在我的消息框之前有错误文本)this-> close();不起作用。有没有办法如何禁用Sqlite驱动程序显示的消息框?
第二个问题是我的错误处理代码看起来多余。有几个查询和数据库连接,它看起来像这样:
QSqlDatabase dbase = QSqlDatabase::addDatabase("QSQLITE", "newdatabase");
dbase.setDatabaseName(sqlFile);
if (!dbase.open())
{
// Several lines of error handling
}
QString firstQueryStr = "FIRST SQL QUERY;";
QSqlQuery firstQuery(QSqlDatabase::database("newdatabase"));
if(!firstQuery.exec(firstQueryStr))
{
// Again that (almost) several lines of error handling
// as well as new several lines of cleanup
}
QString secondQueryStr = "SECOND QUERY;";
QSqlQuery secondQuery(QSqlDatabase::database("newdatabase"));
if(!secondQuery.exec(secondQueryStr))
{
// One more time the same lines of error handling
// as well as the same lines of cleanup
}
在c#中我会使用try catch,我的代码会很整洁。我在Qt中没有找到这样的例子。我不能把几个查询放在一个,因为驱动程序不支持它。我可以通过调用自己的函数或(可能)通过抛出自定义异常来处理这些错误,但我不确定它是否是最好的方法。在这种情况下,我应该怎么做才能在Qt中实现整洁的代码?我是Qt的新手,感谢任何帮助。