ubuntu下 或windows Qt连接SQLLite代码

来源:互联网 发布:文华财经 mac版 编辑:程序博客网 时间:2024/05/17 07:29

 

在Qt Creator中新建一个工程,在工程里面别忘记加上,QT+=sql,下面是测试代码:

#include <QtCore/QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

     QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");  // 使用SQLLite数据库驱动

     db.setHostName("localhost");
     db.setDatabaseName("test");  // 之前建立的数据库
     db.setUserName("root");
     db.setPassword("root");

     if(!db.open()){
         qDebug()<<"Unable to open database";
     }else{
         qDebug()<<"Database connection established";
     }

     return a.exec();
}

成功时就能输出Database connection established