QT连接mysql数据库.(连接驱动方法看前面发的)

时间:2022-11-01 04:54:42

头文件:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include <QSqlDatabase>
#include <QSqlError>
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();


 
private:
    Ui::MainWindow *ui;
};
 
#endif // MAINWINDOW_H
 

main.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(listInforSlot()));
    QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("teachers");
    db.setUserName("root");
    db.setPassword("FORGETme11");
    bool ok=db.open();
    if(ok){
 
    }
    else{
        QMessageBox msgBox;
        msgBox.setText("Error connect database!"+db.lastError().text());
        msgBox.exec();
    }
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::listInforSlot(){
      QSqlTableModel *model=new QSqlTableModel;
      model->setTable("infors");
      model->setFilter("age>=35");
      model->select();
    for(int i=0;i<model->rowCount();i++)//rowcount为AGE大于35的个数
    {
        QSqlRecord record=model->record(i);
        int id=record.value("id").toInt();
        QString name=record.value("name").toString();
        QString add=record.value("address").toString();
        int age=record.value("age").toInt();
         cout<<id<<".."<<qPrintable(name)<<".."<<qPrintable(add)<<".."<<age<<endl;//qPrintable是输出的中文数据不乱码
 
    }
      ui->tableView->setModel(model);//把数据展现在QTableView上
}
 
 


 mainwindow.cpp 

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
 
MainWindow::~MainWindow()
{
    delete ui;
}