Postgresql Qt程序在连接到QPSQL失败时崩溃
我正在尝试通过交叉电缆或无线连接到QPSQL数据库。当我输入正确的详细信息时,一切正常,但是如果我输入错误的详细信息,程序就会崩溃,而不是给我qDebug消息为什么Postgresql Qt程序在连接到QPSQL失败时崩溃,postgresql,qt,Postgresql,Qt,我正在尝试通过交叉电缆或无线连接到QPSQL数据库。当我输入正确的详细信息时,一切正常,但是如果我输入错误的详细信息,程序就会崩溃,而不是给我qDebug消息为什么 const char* driverName = "QPSQL"; QSQLDbHelper* qSQLDbHelper = new QSQLDbHelper(driverName); postgres_db = qSQLDbHelper->connect(host,database,username,password,por
const char* driverName = "QPSQL";
QSQLDbHelper* qSQLDbHelper = new QSQLDbHelper(driverName);
postgres_db = qSQLDbHelper->connect(host,database,username,password,port);
if(postgres_db->open())
{
qDebug() <<"Opened Postgres Database"<< postgres_db->open();
}
else
{
qDebug() << "Something went Wrong:" << postgres_db->lastError().text();
}
qSQLDbHelper->disConnect();
delete qSQLDbHelper;
void QSQLDbHelper::disConnect()
{
qDebug() << "Disconnected From Postgres Database!";
postgres_db->close();
}
const char*driverName=“QPSQL”;
QSQLDbHelper*QSQLDbHelper=新的QSQLDbHelper(driverName);
postgres_db=qSQLDbHelper->connect(主机、数据库、用户名、密码、端口);
如果(postgres_db->open())
{
qDebug()在连接失败时connect()
返回空值:
QSqlDatabase* QSQLDbHelper::connect( const QString& server,
const QString& databaseName,
const QString& userName,
const QString& password )
{
db->setConnectOptions();
db->setHostName(server);
db->setDatabaseName(databaseName);
db->setUserName(userName);
db->setPassword(password);
if(db->open()) {
return db;
}
else {
return NULL;
}
}
因此,您正在这样做:
qDebug() << "Something went Wrong:" << NULL->lastError().text();
但当然,它不会进行实际的连接,而是设置它的属性,所以名称会有点混淆
另一种方法是测试postgres_db是否为NULL,并通过创建某种getter或将其更改为public来访问私有属性qSQLDbHelper->db
。在连接失败时connect()
返回NULL:
QSqlDatabase* QSQLDbHelper::connect( const QString& server,
const QString& databaseName,
const QString& userName,
const QString& password )
{
db->setConnectOptions();
db->setHostName(server);
db->setDatabaseName(databaseName);
db->setUserName(userName);
db->setPassword(password);
if(db->open()) {
return db;
}
else {
return NULL;
}
}
因此,您正在这样做:
qDebug() << "Something went Wrong:" << NULL->lastError().text();
但当然,它不会进行实际的连接,而是设置它的属性,所以名称会有点混淆
另一种方法是测试postgres\u db
是否为NULL,并通过创建某种getter或将其更改为public来访问私有属性qSQLDbHelper->db
。您的答案是正确的,但我有点困惑,如果连接失败,我会返回什么以便它不会崩溃。如果可以,请编辑connect
>函数返回db->open()
并创建新函数来访问属性QSQLDbHelper->db
。然后,如果connect
返回false,您可以在其上使用。我更新了我的答案,介绍了如何解决此问题的两种方法。使用此帮助程序,您无法检查connect上的错误。您需要编辑该类。您的答案是正确的,但我有点怀疑不知道在连接失败时会返回什么,这样它就不会崩溃。如果可以,请编辑connect
函数以返回db->open()
并创建新函数来访问属性QSQLDbHelper->db
。然后,如果connect
返回false,您可以在该函数上使用。我更新了我的答案,并介绍了如何解决此问题的两种方法。使用此帮助程序,您无法检查connect上的错误。您需要编辑该类。