处理QSqlDatabase
的连接的正确方法是什么?
在我的程序中,我这样做:
DatabaseConnector *databaseConnector = 0;
try
{
databaseConnector = new DatabaseConnector();
//Do stuff...
delete databaseConnector;
}
catch(QString e)
{
delete databaseConnector;
QMessageBox::information(this,"Error",e);
}
databaseConnector.h
#ifndef DATABASECONNECTOR_H
#define DATABASECONNECTOR_H
#include <QtSql>
class DatabaseConnector
{
public:
DatabaseConnector();
DatabaseConnector(QString hostname, QString database, QString user, QString password);
~DatabaseConnector();
private:
QSqlDatabase db;
};
#endif // DATABASECONNECTOR_H
databaseconnector.cpp
#include "databaseconnector.h"
#include <QString>
DatabaseConnector::DatabaseConnector()
{
QSettings settings;
db = QSqlDatabase::addDatabase("QIBASE");
db.setHostName(settings.value("db/host").toString());
db.setDatabaseName(settings.value("db/name").toString());
db.setUserName(settings.value("db/user").toString());
db.setPassword(settings.value("db/pass").toString());
if(!db.open())
{
QString databaseConnectionError = db.lastError().text();
throw databaseConnectionError;
}
}
DatabaseConnector::DatabaseConnector(QString hostname, QString database, QString user, QString password)
{
db = QSqlDatabase::addDatabase("QIBASE");
db.setHostName(hostname);
db.setDatabaseName(database);
db.setUserName(user);
db.setPassword(password);
if(!db.open())
{
QString databaseConnectionError = db.lastError().text();
throw databaseConnectionError;
}
}
DatabaseConnector::~DatabaseConnector()
{
db.close();
}
即使我使用QSqlDatabase::removeDatabase(db.connectionName());
QSqlDatabasePrivate :: addDatabase:重复的连接名称'qt_sql_default_connection',删除旧连接。
答案 0 :(得分:6)
通常,您不需要在应用程序中多次打开数据库连接。
添加数据库时,您可以命名连接:
QSqlDatabase::addDatabase( "QIBASE", "MyDBConnectionName" );
您可以使用该名称来查询连接:
if( QSqlDatabase::contains( "MyDBConnectionName" ) )
{
QSqlDatabase db = QSqlDatabase::database( "MyDBConnectionName" );
//Do stuff...
}
else
{
// connection not found, do something
}
另请注意,在调用QSqlDatabase::removeDatabase
之前,您应断开数据库连接:
db.close();
QSqlDatabase::removeDatabase("MyDBConnectionName");
答案 1 :(得分:0)
要添加新数据库,您需要为其命名。如果未指定唯一名称,则会重新使用默认数据库。这在类引用中有记录。
尝试:
db = QSqlDatabase::addDatabase("QIBASE", databaseName);
答案 2 :(得分:-2)
在主应用中:
Request
在第二个应用中:
QSqlDatabase db =QSqlDatabase::addDatabase( "QSQLITE");