QT7 How to connect Qt to SQLite

来源:互联网 发布:幸运双色球过滤软件 编辑:程序博客网 时间:2024/06/08 08:39

1. create a qt widgets application, name it as Sqlite_DB, modify the class name as Login

2. switch to ui designer, drag a label onto the window used for showing the prompting information

3. modify the login.h file as follows:

#ifndef LOGIN_H#define LOGIN_H#include <QMainWindow>#include <QtSql>#include <QDebug>#include <QFileInfo>namespace Ui {class login;}class login : public QMainWindow{    Q_OBJECTpublic:    explicit login(QWidget *parent = 0);    ~login();private:    Ui::login *ui;};#endif // LOGIN_H

4. modify the login.cpp file as follows:

#include "login.h"#include "ui_login.h"login::login(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::login){    ui->setupUi(this);    QSqlDatabase mydb = QSqlDatabase::addDatabase("QSQLITE");    mydb.setDatabaseName("C:/work_files/sqlite-tools-win32-x86-3110100/company.db");//note: the separator used in the path must be forward slash, or errors will occur     if(!mydb.open())        ui->label->setText("Failed to open the database");    else        ui->label->setText("Connected...");}login::~login(){    delete ui;}

5. run the project




0 0