Qt数据库加载驱动并连接

//头文件

#include 
#include 
#include 
#include 

//从ini文件中读取数据库相关ip、name

bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");//添加数据库驱动
    QSettings m_set(qApp->applicationDirPath() + "/config/" + "SPSDB.ini", QSettings::IniFormat);
    QString ip = m_set.value("DBInfo/ip").toString();
    QString dbname = m_set.value("DBInfo/dbname").toString();
    QString dbuser = m_set.value("DBInfo/dbuser").toString();
    QString dbpwd = m_set.value("DBInfo/dbpwd").toString();

    db.setHostName(ip);
    db.setDatabaseName(dbname);
    db.setUserName(dbuser);
    db.setPassword(dbpwd);
    if (!db.open())
    {
        QMessageBox::critical(0, QObject::tr("Database Error"), db.lastError().text());
        return false;
    }
    return true;
}

//通常情况下,是在main函数中调用createConnection()的

int mian(int argc,char *argv[])
{
    QApplication app(argc,argv);
    if(!createConnection())
    {
        return 1;
    }
    return app.exec();
}

你可能感兴趣的:(C++GuiQt4编程)